【发布时间】:2019-11-17 20:42:54
【问题描述】:
我必须从文件行中解析数据,为此我现在使用 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("%lu\n%s\n", numberOfVer, ptr); // Here I test the values, I expect to get 1 followed by newline and abc
if (numberOfVer == 0 || *ptr != '\0') { // Not a positive number or there exists something after the amount!
fprintf(stderr, INVALID_IN);
return EXIT_FAILURE;
}
但是,ptr 字符串不是“abc”或“abc”,它是一个空字符串... 这是为什么?根据文档,它必须是“abc”。
【问题讨论】:
-
What can I use for input conversion instead of scanf? 的可能重复项(是的,我知道这是自我推销,但它回答了问题——使用
fgets)