?
Solved

Command line arguments

Posted on 2002-05-21
12
Medium Priority
?
916 Views
Last Modified: 2010-04-02
I am trying to use command line arguments to input a string(or just a array of char)
this is the code i am using..

#include <cstdio>
int main(int argc, char** argv)
{
char* word;
sscanf(argv[1], "%s", &word);

...}

my program crashes when i try to access WORD and when i use COUT statements to see what WORD contains.. it would output weird characters.

could you tell me how to correctly input commmand line arguments..
0
Comment
Question by:grfik
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +3
12 Comments
 
LVL 30

Expert Comment

by:Axter
ID: 7025955
word needs to have memory assigned to it.
Example:
int main(int argc, char** argv)
{
char word[32];
sscanf(argv[1], "%s", &word);
0
 
LVL 30

Expert Comment

by:Axter
ID: 7025961
You should also check that argc is at least equal to two.
Example:
int main(int argc, char* argv[])
{
     char word[32];
     if (argc > 1) sscanf(argv[1], "%s", &word);
     
     printf("argv[1] = %s\n", word);

     system("pause");
     return 0;
}

0
 

Author Comment

by:grfik
ID: 7026102
this is my main() function

int main(int argc, char** argv)
{
   if(argc < 2)
   {
      cout << "Must enter a word as a command line argument\n";
      return 0;
   }

   char w[90];

   Stack<char> s;
   Queue<char> q;

   sscanf(argv[1], "%s", &w);

   /*
   int i = 0;
   while(w[i] != '\n')
   {
      s.push(w[i]);
      q.add(w[i]);
      i++;
   }
   */

   char word;
   char ans = 'n';
   do
   {
      Stack<char> s;
      Queue<char> q;

      if(ans != 'n' && ans != 'N')
      {
         cout << "Enter a word: ";
         cin.get(word);

         while (word != '\n')
         {
            s.push(word);
            q.add(word);
            cin.get(word);
         }
      }


      bool check = true;
      try
      {
         while ( ! q.isEmpty( ) )
            if(s.pop() != q.remove())
            {
               check = false;
               break;
            }
      }
      catch (QueueEmpty qe)
      {
         cout << qe.getMessage();
      }

      if(check)
         cout << "The word is a palindrome\n";
      else
         cout << "The word is not a palindrome\n";

      cout << "Again?(y/n): ";
      cin >> ans;
      cin.ignore(10000, '\n');
   }while (ans != 'n' && ans != 'N');

   return 0;
}

i commented a part so the program executes..

as you can see i attempt to access individual characters from the command line argument..
but since the char is initialized at a array of size 90
"char w[90]"

so i cant test for the end of the word..
there is no null character :(

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 49

Expert Comment

by:DanRollins
ID: 7026416
The thing is... you may not need to use sscanf at all (I have never liked that function).

argv[1] is the first word, argv[2] is the second word etc.

For instance, if the command line is:

     MyProg.Exe now is the time for all good beans

then argc is 9
and
argv[1] is the address of "now"
argv[2] is the address of "is"
argv[3] is the address of "the"
argv[4] is the address of "time"
argv[5] is the address of "for"
argv[6] is the address of "all"
argv[7] is the address of "good"
argv[8] is the address of "beans"

If you do use sscanf, you really should pass in the address of the destination buffer:

   sscanf(argv[1], "%s", word );
or
   sscanf(argv[1], "%s", &word[0] );

(rather than &word) even though the compiler seems to accept either form in this case.  It's just a good habit.

-- Dan
0
 

Author Comment

by:grfik
ID: 7026432
the problem is then that i have to specify a size for array of characters WORD
for some reason i cant test for the null character..
the rest of the array gets filled with random characters which causes alot of problems
0
 
LVL 49

Accepted Solution

by:
DanRollins earned 200 total points
ID: 7026591
Thew code that you showed was not checking for null.  You showed:

 int i = 0;
  while(w[i] != '\n')
  {
     s.push(w[i]);
     q.add(w[i]);
     i++;
  }

but that is only checking for \n.  You need to make the first line look like:

  while( w[i] != '\0')
or perhaps this:
  while( !w[i] )

-- Dan


0
 
LVL 1

Expert Comment

by:Ilango
ID: 7026784
If your real problem is with accessing commandline parameter (the part which you commented out) herez the fix.

/*
  int i = 0;
  while(w[i] != '\0')
  {
     s.push(w[i]);
     q.add(w[i]);
     i++;
  }
*/

Also if you recoin the word from letters make sure you manually insert String terminator ('\0') at the end.
0
 
LVL 1

Expert Comment

by:thegroup
ID: 7026964
You could simply use the strings.

if (argc > 1)
{
  // process command line options
  for (int i=1; i <= argc; i++)
  {
    // process i parameter
    do_something (argv[i]);
  }
}
0
 

Expert Comment

by:0xDEADBEEF
ID: 7027582
#include <stdio.h>
#include <iostream.h>

int isPalindrome(char *str){
  char *pbeg = str, *pend = str + strlen(str) - 1;

  while(pbeg < pend){
    if(*pbeg != *pend) return 0; //false
    pbeg--;
    pend--;
  }
  return 1; //true
}

void main(int argc, char* argv[]){
  if (argc < 2) cout << "must enter a word at least" << endl;
  else {
    for(int i = 0; i < argc; i++){
      cout << argv[i] << " is " << isPalindrome(argv[i]) ? "" : "not " << "a palindrome" << endl;
    }
  }
}

I didn't compile this actually, but I think it should work. Hope this helps.
0
 

Expert Comment

by:0xDEADBEEF
ID: 7027591
Oops. In isPalindrome, pbeg has to be incremented of course. See what happens if you don't proofread your code? ;-)
0
 

Author Comment

by:grfik
ID: 7027804
ooooopsss
i was checking for \n all this time while i should've been checking for \0
thx dan
and the way i actually ended up implementing the code was..
   int i = 0;
   while (argv[1][i] != '\0')
   {
      s.push(argv[1][i]);
      q.add(argv[1][i]);
      i++;
   }
sry if i worded the question so it seemed more complicated then it should be.. :/

thank you all
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 7027879
They don't call me eagle-eye Dan fer nuthin!  Good luck -- Dan
0

Featured Post

Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question