我需要从文件中读取单独的数字,然后在代码中使用它们。
例如,文件会说
之类的内容2 5
8 9
22 4
1 12
现在我有:
while(fgets(line, MAX_LEN, in) != NULL)
{
ListRef test = newList();
token = strtok(line, " \n");
int x = token[0] - '0';
int y = token[2] - '0';
}
哪个工作正常,除非一个或两个数字是多位数。我怎么能改变它来读取这两个数字(总会有两个,就是这个),不管它们的长度如何?
答案 0 :(得分:1)
while (fgets(line, sizeof(line), in) != NULL)
{
int x, y;
if (sscanf(line, "%d %d", &x, &y) != 2)
...report format error...
...use x and y as appropriate...
}
答案 1 :(得分:0)
根据line
中的一行数字(如while
循环中所示),您可以这样做:
char *p;
p = strtok(line, " \n");
while (p != NULL) {
sscanf(p, "%d", &num);
/* do something with your num */
p = strtok(NULL, " \n");
}
但请注意strtok
可能存在线程安全问题。见strtok function thread safety
如果您只想阅读所有数字,无论哪一行,只需使用fscanf
:
while (fscanf(in, "%d", &num) == 1) {
/* do something with your num */
}