我试图从 C 中的文本文件中读取一行,但是输出表示错误。我想我在我的代码中做错了分隔符。有人可以帮忙吗?
正文:
hello, world, 1, 2, bye
输出:
hello world 12576 117453344 bye
typedef struct structure {
char hello[25];
char world[25];
int num1;
int num2;
char bye[25];
} Hello;
主要内容:
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include "structure.h"
using namespace std;
int main(int argc, char **argv) {
char line[25];
FILE *fp;
fp = fopen("text.txt", "r");
Hello c;
while (fgets(line, sizeof(line), fp) != NULL) {
sscanf(line, "%[^','],%[^','],%[^','],%[^','],%s",
c.hello, c.world, &c.num1, &c.num2, c.bye);
}
printf("%s %s %d %d %s", c.hello, c.world, &c.num1, &c.num2, c.bye);
return 0;
}
最佳答案
不要使用 %[^',']
读取整数。 %d
应该被使用并且也只是忽略 ','
在字符串中使用说明符 %[^,]
在 sscanf
。
并检查它的返回值。
关于C - sscanf 在读取文件后给我错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523013/