简体   繁体   English

字符串二维数组

[英]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. 这是一段代码,用于声明一个最多包含16个值和10个名称的字符数组,一条语句以字符串形式读取字符数组,然后使用%s格式字符将其打印为字符串。 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. 用键盘输入名称后,ctrl + d不会显示任何内容。

Ex enter: 输入:

linus 莱纳斯

chenxi 陈溪

yangzi 扬子

ctrl+d Ctrl + D

As written, your code tries to read 10 names no matter what. 如所写,您的代码无论如何都尝试读取10个名称。

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. 要在文件末尾退出(例如,在某些操作系统中通过输入control-D ENTER),则需要在读取数据的循环中检查文件末尾。 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. 请参见手册页的scanf并查找EOF。

You might also want to print each name with a newline at the end. 您可能还希望在每个名称的结尾加上换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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