将输入文件拆分为单独的数字,然后将它们用作程序的输入

时间:2013-01-09 17:06:08

标签: c file input strtok split

我正在使用代码块并且遇到了障碍,我希望从.txt文件中获取两个数字并使用它们分配给不同的常量。

在输入.txt文件中说有10,20我想让a = 10和b = 20,然后继续使用这些数字进行进一步的计算。

在过去,我使用'strtok'从文件中分割出一个字符串,其中(“,:”)是定界字符串。

FILE *fp; char s[1000];
fp=fopen("chris.txt","r"); // opens the file


if (!fp) return 1;
while (fgets(s,1000,fp)!=NULL); //makes the stuff inside the file defined as string s


char*pch;printf("Splitting string \"%s\" into tokens:\n",s);
pch = strtok (s,",");
while (pch !=NULL)
{
printf ("%s\n",pch);
pch= strtok(NULL," ,0.");
}

我在想我可以遵循类似的方式,但不知何故将不同的数字分配给不同的常量。有关如何解决这个问题的想法吗?

2 个答案:

答案 0 :(得分:1)

int a, b;

if (sscanf(s, "%d,%d", &a, &b) != 2) {
    // Error, the format was not "<int>,<int>" 
}

您甚至可以使用scanf直接从文件中读取

if (fscanf(fp, "%d,%d", &a, &b) != 2) {

答案 1 :(得分:0)

使用wxWidgets框架我通常使用wxTextInputStream来执行这些任务。点击链接查看示例。

如果wxWidgets不是你的话,它可能会给你一些想法。

相关问题