如果我有一个文件,其中一行包含 12,1
,如何拆分数字并将它们放入 2 个变量中?例如,变量 a
将获取 12
,另一个变量 b
将获取 1
。
最佳答案
第一种方法:
我们使用fscanf()我们输入我们期望文件具有的格式。我们循环,直到函数的返回值小于我们期望读取的数字。
#include <stdio.h>
int main(void)
{
FILE *fp;
if ((fp = fopen("test.txt", "r")) == NULL)
{ /* Open source file. */
perror("fopen source-file");
return 1;
}
int a, b;
while(fscanf(fp, "%d,%d", &a, &b) == 2)
{
printf("%d %d\n", a, b);
}
fclose(fp);
return 0;
}
<小时/>
第二种方法:
我们和fgets()一起阅读进入缓冲区,然后我们在 strtok() 的帮助下进行分割,使用分隔符(本例中为逗号)。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define bufSize 1024
int main(void)
{
FILE *fp;
char buf[bufSize];
if ((fp = fopen("test.txt", "r")) == NULL)
{ /* Open source file. */
perror("fopen source-file");
return 1;
}
char* pch;
int a, b, i;
while (fgets(buf, sizeof(buf), fp) != NULL)
{
i = 0;
// eat newline
buf[strlen(buf) - 1] = '\0';
pch = strtok (buf,",");
while (pch != NULL)
{
// read first number
if(!i++)
a = atoi(pch);
else // read second number
b = atoi(pch);
pch = strtok (NULL, ",");
}
printf("%d %d\n", a, b);
}
fclose(fp);
return 0;
}
代码基于我的示例 here .
<小时/>两个示例都假设我们有 test.txt,如下所示:
1,2
3,4
PS - 确保下次你表现出一些努力。 :)
关于c - 如何将文件中的逗号分隔行拆分为 C 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786911/