简体   繁体   中英

how to print a string vertically in c?

Ok the output is supposed to look like this:

./a 3 4 8 2  
3  
4  
8  
2  

This is what I have so far, but I am lost and can only get the first integer to print (we have to use GetInt, which gets the specified integer in the string):

int main (int argc, char*argv []){  
   int v;    
   int i;  
   i = 1;  
   v = GetInt(argc, argv, i + 1);  

   if(argc >= 1){  
      printf("%d\n", GetInt(argc, argv, i));  
   }  
   return 0;  
}  

看起来您需要使用一个for循环来依次获取每个值。

Without actually seeing your implementation of GetInt, something like this (Assumes C90):

#include <stdio.h>

int GetInt( int argc, char* argv[], int i ) {
    /* 
     * you may want to use sscanf, strtol or other functions,
     * but you haven't specified
     */
    return atoi( argv[i] );
}

int main ( int argc, char* argv[] ) {
    int i;
    for ( i = 1; i < argc; ++i ) {
        printf( "%d\n", GetInt( argc, argv, i ) );
    }
    return 0;
}

Returns:

$ ./a.out 3 4 8 2
3
4
8
2

Error checking omitted and such. It is an exercise to you to figure out how to deal with non-decimal arguments.

As a note, why do you have to use GetInt() ? It's completely superfluous and not part of a standard library, and unless you wrote it yourself (or in class), I can't imagine ever using it. This is what I would do:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;
    for(i = 1; i < argc; i++)
      {
        printf("%s\n", argv[i]);
      }
    return 0;
}

I know it doesn't use GetInt() , but it's shorter, and you probably shouldn't be using GetInt() because it's kind of useless. Plus, there's already an atoi() function and, if you don't want to use that because it's outdated, a strtol() function you can recast as an int if you have to.

I'm not citicizing you or anything, I'm just wondering why you're being required to use this superfluous, nonstandard function.

Use printf() in a loop. argc is the number of white space separated arguments in argv[], in the example above, argc = 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM