我想读取用户输入并将其作为包括空格在内的字符串存储。我搜索了解决方案,被指向使用fgets()或scanf(%[^\n], str)。但是这两种方法都给我一个错误。
这是我的代码:
//MAX_CHARACTERS is set to 30
scanf("%d", &input);
if (input == 1){
int pr;
char na[MAX_CHARACTERS+1];
printf("\nEnter the name: ");
scanf("%[^\t\n]", &na);
while (strlen(na)>MAX_CHARACTERS){
printf("\nName is too long, enter new name: ");
scanf("%[^\t\n]", &na);
}// end na check
printf("\nEnter priority: ");
scanf("%d", &pr);
while (pr>MAX_PRIORITY || pr <MIN_PRIORITY){
printf("\nBad priority, enter new priority (0-100): ");
scanf("%d", &pr);
}//end pr check
如果我在所有的
%[^\t\n]
实例中使用%s
,那么它可以正常工作,但是当我使用%[^\t\n]
或fgets(na, 30, stdin)
时,它会跳过第一个输入名字的scanf()直接到"Enter priority:"。然后当我打印时,我的名字被留空,带着我输入的优先级。编辑:对不起,第一个scanf()缺少引号是个错别字,不是问题的原因。我为第一个scanf("%d", input)输入了'1'。修复了它。由于我还不能发表回答,有人找出了问题所在。如果还有人感兴趣,问题是第一个scanf()。scanf("%d", &input);
这段代码在缓存中留下了一个换行符“\n”。第二个代码将读取该换行符作为输入,因此它被跳过了。
解决方案:
添加一个
fflush(stdin); //right after the if statement seems to have fixed the issue.
感谢大家的帮助。
scanf
,但是如果要读取一个字符串,你的参数应该是一个char*
,即na
或&na[0]
。但是我没有看到任何%s
格式说明符。 - Kerrek SBscanf()
或sscanf()
返回的值。 (如果输入不是数字,那么(scanf("%d", &input);
会发生什么,请三思。) - Keith Thompson