What does gets() save when it reads just a newline
这是Prata的C Primer Plus中
It gets a string from your system's standard input device, normally
your keyboard. Because a string has no predetermined length,gets()
needs a way to know when to stop. Its method is to read characters
until it reaches a newline (\ ) character, which you generate by
pressing the Enter key. It takes all the characters up to (but not
including) the newline, tacks on a null character (\\0 ), and gives the
string to the calling program.
我很好奇
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
这是我与程序的互动:
1 2 3 4 5 6 7 8 9 10 11 | $ ./a.out This is some string This is the input as a string: This is some string Is it the string end character? 0 Is it a newline string? 0 Is it the empty string? 0 This is the input as a string: Is it the string end character? 0 Is it a newline string? 0 Is it the empty string? 0 |
当我按下所有输入键时,第二个块实际上就是感兴趣的东西。在那种情况下
It takes all the characters up to (but not including) the newline
最好说它采用了包括换行符的所有字符,但存储了不包括换行符的所有字符。
因此,如果用户输入
因此,如果仅按enter,则
printf("This is the input as a string: %s\
", input);
这里没问题,尽管您可能希望用一些人工字符来分隔字符串以进行更好的调试:
printf("This is the input as a string: '%s'\
", input);
printf("Is it the string end character? %d\
", input == '\\0');
不好:您要在此处检查1个字节,而不是整个缓冲区。如果您尝试将整个缓冲区与0进行比较,答案始终是
正确的方法是:
printf("Does the first byte contain the string end character? %d\
", input[0] == '\\0');
这与
printf("Is it a newline string? %d\
", input =="\
");
不好:这会将缓冲区的地址与
"
printf("Is it a newline string? %d\
", strcmp(input,"\
") == 0);
请注意特殊用法:
printf("Is it the empty string? %d\
", input =="");
这里是同样的错误。在此也使用
printf("Is it the empty string? %d\
", strcmp(input,"") == 0);
人们常说的
BTW,
1 2 3 4 5 |
这可能导致混乱:
它将字符串设置为