这个问题在这里已有答案:
我试图从控制台上的用户输入接受多字符串。我的代码看起来像..
char fullPath[150];
char fileName[30];
char serviceName[50];
int portNum[6];
char ip[16];
printf("Enter full path where you want the file to be.\nExample: C:\\Users\n");
scanf("%s", fullPath);
CheckDirectory(fullPath);
printf("Enter what you want the file to be named. \nExample: test.exe\n");
scanf("%s", fileName);
CopyNewFile(fullPath, fileName, argv[0]);
printf("Enter RunKey Service Name:\n");
fgets(serviceName,49,stdin);
printf("Enter callback IP:\n");
scanf("%15s", ip);
printf("Enter callback port:\n");
scanf("%5s", portNum);
我遇到的问题是......
Enter RunKey Service Name:
Enter callback IP:
192.168.100.10
Enter callback port:
443
如您所见,它会跳过我应该输入服务名称的部分。我已经尝试过像其他两个输入一样使用scanf,我也试过使用正则表达式(%[^ \ n])并且它也没有抓住整行。
编辑:经过更多测试后,如果我将printf和scanf移动到printf上面,询问文件应该在哪里,我可以输入服务名称。
事情是在之前的输入scanf
输入的\n
仍然在stdin
- 不是下一行中的fgets
消耗它。放一个假的getchar()
来摆脱它。
printf("Enter what you want the file to be named. \nExample: test.exe\n");
scanf("%s", fileName);
getchar();//<----
另一件事是portNum
是int
类型 - 你不能使用%s
格式说明符读入int
变量 - 这是未定义的行为。 (不传递scanf
中格式说明符所要求的正确类型的参数)。
你也可以使用fgets(serviceName,50,stdin);
fgets
将根据它的容量读取它 - 不需要自己限制它。
另一件事是检查scanf
和fgets
的返回值。
为了更清楚 - 当获得字符串输入时为什么使用scanf
而不是fgets
- 你可以使用简单的fgets
并获得输入。另外一点是查看scanf
和fgets
的手册。为您举例说明如何检查scanf
和fgets
的返回值。
if( scanf("%s", fileName)!= 1){
fprintf(stderr,"%s\n","Error in input");
exit(EXIT_FAILURE);
}
并以这种方式也为fgets
if( fgets(serviceName, 50, stdin) == NULL ){
fprintf(stderr,"%s\n","Error in input");
exit(EXIT_FAILURE);
}