[英]Reading in a string with spaces in C
我试图读取一个字符串,可能包括也可能不包括空格ex。 “你好,世界”。 通过用户输入的数字选择菜单进行以下操作。 这只是我想要做的一个小复制品。
#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更改行之后,它会打印语句询问我想要替换它的内容并自动输入任何内容然后打印字符串,第一个字符串为空?
我也尝试用sscanf("%[^\\n\\t]s", line[0]);
读取该行sscanf("%[^\\n\\t]s", line[0]);
没有运气。 有任何想法吗?
这是因为
scanf("%d",&option);
在stdin中保留\\n
字符,并在第一次调用fgets()
。 这就是为什么最好完全避免C中的scanf()
。
你可以修复它:
scanf("%d",&option);
getchar(); /* consume the newline */
但我建议使用fgets()
来读取option
,然后你可以使用strtol()
将其转换为整数。
请注意,此语句可能不是您想要的(这限制了您可以读入line[0]
)。
fgets(line[0],strlen(line[0]),stdin);
你可能想要使用:
fgets(line[0],sizeof line[0],stdin);
这样你就可以读到line[0]
的实际大小。
请阅读C Faq条目: http : //c-faq.com/stdio/scanfprobs.html
使用fgets()
通常看起来不像使用scanf()
容易出错,但是如果用户输入的字符串与指定的最大字符数一样长或更长,则任何多余字符(包括换行符)都会保留在输入流。 出于这个原因,我通常编写自己的gets()
版本来获取用户的输入字符串,如果我想要数字输入,我使用strtol()
。 以下是此类功能的示例:
char * s_gets(char *st, int n)
{
char *ret;
int ch;
ret = fgets(st, n, stdin);
if (ret) {
while (*st != '\n' && *st != '\0')
++st;
if (*st)
*st = '\0';
else {
while ((ch = getchar()) != '\n' && ch != EOF)
continue; // discard extra characters
}
}
return ret;
}
应用于OPs问题,我可能会这样做:
#include <stdlib.h> // for strtol()
...
char buf[80];
int option = 0;
printf("would you like to replace line 1? (1 for yes)\n");
s_gets(buf, sizeof(buf));
option = strtol(buf, NULL, 10);
if(option==1){
printf("what would you like to replace the line with?\n");
s_gets(line[0],sizeof(line[0]));
}
你的问题是'\\n'
字符留在stdin
并由fgets
。
我建议你总是使用fgets
进行读取输入,所以
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char line[3][80];
char temp[3];
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");
fgets(temp,sizeof(temp),stdin);
option = atoi(temp);
if(option==1){
printf("what would you like to replace the line with?\n");
fgets(line[0],sizeof(line[0]),stdin);
}
for(int i = 0; i < 3; i++){
printf("%s", line[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.