从用户输入接受多字串并分配给char数组

时间:2018-01-20 16:20:55

标签: c

我正在尝试从控制台上的用户输入接受多字符串。我的代码看起来像..

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上方,询问文件应该在哪里,我可以输入服务名称。

1 个答案:

答案 0 :(得分:1)

事情在上一个输入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根据其容量阅读它 - 无需自行限制。

另一件事是检查scanffgets的返回值。

更清楚一点 - 在获取字符串输入时,为什么要使用scanf代替fgets - 您只需使用fgets并获取输入。另外一点是查看scanffgets的手册。为您举例说明应如何检查scanffgets的返回值。

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);    
}
相关问题