用C中的空格读取字符串 [英] Reading in a string with spaces in C
问题描述
我正在尝试读取可能包含或不包含空格的字符串.你好,世界".通过对用户输入的数字选择菜单进行以下操作.这只是我正在尝试做的一小部分复制品.
I am trying to read in a string that may or may not include spaces ex. "hello world". By doing the following with a number select menu that is inputted by the user. This is just a small replica of what I am trying to do.
#include <stdio.h>
#include <string.h>
int main(void){
char line[3][80];
strcpy(line[0],"default line 1\n");
strcpy(line[1],"default line 2\n");
strcpy(line[2],"default line 3\n");
for(int i = 0; i < 3; i++){
printf("%s", line[i]);
}
int option = 0;
printf("would you like to replace line 1? (1 for yes)\n");
scanf("%d",&option);
if(option==1){
printf("what would you like to replace the line with?\n");
fgets(line[0],strlen(line[0]),stdin);
}
for(int i = 0; i < 3; i++){
printf("%s", line[i]);
}
}
为什么在输入1来更改行后为什么打印出询问我要替换为什么的语句,并自动输入什么内容,然后将第一个字符串打印为空的语句自动显示?
Why is it that after I enter 1 to change the line, it prints the statement asking what I want to replace it with and will automatically enter nothing then printing the strings with the first one as empty?
我也已经尝试用 sscanf(%[^ \ n \ t] s",line [0]);
读取该行,但是没有任何运气.有什么想法吗?
I also have already tried reading the line with sscanf("%[^\n\t]s", line[0]);
without any luck. Any ideas?
推荐答案
是因为
scanf("%d",&option);
在stdin中保留 \ n
字符,并在第一次调用 fgets()
时使用.这就是为什么最好完全避免在C语言中使用 scanf()
.
leaves the \n
character in stdin and is consumed by the first call to fgets()
.
That's why it's best to avoid scanf()
in C completely.
您可以使用以下方法修复它:
You can fix it with:
scanf("%d",&option);
getchar(); /* consume the newline */
但是我建议也使用 fgets()
来读取 option
,然后您可以使用
But I'd suggest using fgets()
to read option
as well and then you can use strtol()
to convert it into an integer.
请注意,此语句可能不是您想要的(这限制了您可以读入 line [0]
的内容).
Note that this statement is not probably what you intended (which limits what you can read into line[0]
).
fgets(line[0],strlen(line[0]),stdin);
您可能打算使用:
fgets(line[0],sizeof line[0],stdin);
,以便您可以读取到 line [0]
的实际大小.
so that you can read upto the actual size of line[0]
.
请同时阅读C常见问题解答条目: http://c-faq.com/stdio/scanfprobs.html
Please read the C Faq entry as well: http://c-faq.com/stdio/scanfprobs.html
这篇关于用C中的空格读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!