0

I know that this must be a scope problem, but I've tried everything at this point. I just can't seem to save k from argv[1].

int main(int argc, string argv[])  

if argc == 2  
   int k = atoi(argv[1]);  
else  
   return 1;  

If i now try to print k, it doesn't work. What is the best way to save this output, k? Ive watched the shorts on scope, return, etc. I'm just incredibly confused at this point. A hint would be great.

2
  • 1
    What do you mean "it doesn't work?" Do you get an error? Does nothing print out? How are you calling your print function?
    – Air
    Sep 5 '14 at 16:17
  • This does look like a good way to store argv[1] as an int in k. Have you used gdb yet to see what the value of k is here? I think that will tell you what exactly happens. (If you don't know how to use gdb, look for the video on debugging with gdb in the Section/Shorts parts in the next few weeks, it must be in there, and using gdb is an incredibly valuable, timesaving skill.)
    – user11165
    Mar 28 '16 at 13:32
1

First, use

if (argc != 2)
{
    return 1;
}

rather than "== 2", so your main programme doesn't run within the first condition.

The rest of your code looks okay. How did you try printing "k"? Did you use

printf("%d", k);

?

0

Assuming all headerfiles are already included, give a try to this and tell what happens.

int main(int argc, string argv[])  
{
     int k;
     if (argc == 2)
          k = atoi(argv[1]);
     else
          return 1;
     printf("%d",k);
     return 0;
}
2
  • It says that the first "int" is an unexpected expression... Sep 3 '14 at 23:58
  • Edited. I have tested that on Ubuntu 14.04 g++ compiler. The course uses C99(strict). Although that should work now, but if string argv[] doesn't work, then try char* argv[].
    – sinister
    Sep 4 '14 at 13:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .