我必须解析文件行中的数据,为此我现在使用strtol((函数。
例如,我在文本文件中有这样一行:1 abc
例如,这是一个无效的行,因为该特定行必须包含一个且仅包含一个整数值。
现在,当我以这种方式使用strtol时:
FILE *fs;
fs = fopen("file.txt", "r");
char* ptr = NULL; // In case we have string except for the amount
char lineInput[1024]; // The max line size is 1024
fscanf(fs, "%s", lineInput);
long numberOfVer = strtol(lineInput, &ptr, BASE);
printf("%lun%sn", numberOfVer, ptr); // Here I test the values, I expect to get 1 followed by newline and abc
if (numberOfVer == 0 || *ptr != ' ') { // Not a positive number or there exists something after the amount!
fprintf(stderr, INVALID_IN);
return EXIT_FAILURE;
}
但是,ptr字符串不是"abc"或"abc",它是一个空字符串。。。为什么?根据文件,它必须是"abc"。
scanf("%s")
跳过空白。因此,如果你有输入"1 abc"
并用扫描它
fscanf(fs, "%s", lineInput);
lineInput
内容最终为"1"
,并且字符串的其余部分保留在输入缓冲器中,为下一个输入操作做好准备。
读取行的常用功能是fgets()
FILE *fs;
fs = fopen("file.txt", "r");
char* ptr = NULL; // In case we have string except for the amount
char lineInput[1024]; // The max line size is 1024
// using fgets rather than fscanf
fgets(lineInput, sizeof lineInput, fs);
long numberOfVer = strtol(lineInput, &ptr, BASE);
printf("%ldn%sn", numberOfVer, ptr); // Here I test the values, I expect to get 1 followed by newline and abc
// ^^^ numberOfVer is signed
if (numberOfVer == 0 || *ptr != ' ') { // Not a positive number or there exists something after the amount!
fprintf(stderr, INVALID_IN);
return EXIT_FAILURE;
}