简体   繁体   中英

Character String 2D array

A section of code to declare a character array with up to 16 values and 10 names, a statement to read in the character array as a character string, then print them out as a string using the %s format character. Enter a name from the keyboard.

int i;

char name[10][16];

for(i=0; i<10; i++){
   scanf("%s", name[i]);
}

for(i=0; i<10; i++){
   printf("%s", name[i]);
}

After I enter names by keyboard, ctrl+d does't shows up anything.

Ex enter:

linus

chenxi

yangzi

ctrl+d

As written, your code tries to read 10 names no matter what.

To exit on end-of-file (eg by entering control-D ENTER in some operating systems), you need to check for end-of-file in the loop that reads the data. In that case, you'll also need to remember how many values you've read, and only print that number. (If you don't, it'll seem to work but only because the array is initialized to zero. If you used the same array again later, you could get garbled results.)

See the manual page for scanf and look for EOF.

You might also want to print each name with a newline at the end.

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