Solved

Command line arguments

Posted on 2002-05-21
12
912 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
  • 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
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 50 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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
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.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

828 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