Solved

Command line arguments

Posted on 2002-05-21
12
909 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 49

Expert Comment

by:DanRollins
Comment Utility
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
Comment Utility
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
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 1

Expert Comment

by:Ilango
Comment Utility
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
Comment Utility
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
Comment Utility
#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
Comment Utility
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
Comment Utility
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
Comment Utility
They don't call me eagle-eye Dan fer nuthin!  Good luck -- Dan
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
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 use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

743 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now