输入文件,信息以逗号分隔

时间:2014-02-18 17:57:50

标签: arrays input char double strtok

如何读取具有由多行逗号分隔的字符串和双精度的输入文件。我想将字符串保存在像char Teams[5][40]这样的2D数组中。我想对每行数字做同样的事情。因此,对于第二行数字,我需要char probFG[5][10]和第三行probTD [5][10]

我希望每个数字都存储在数组的不同索引中,但我想确保每个数组的所有索引都对应于它们各自的列。

Team1,0.80,0.30
Team1,0.30,0.20
Team1,0.20,0.70
Team1,0.70,0.80
Team1,0.90,0.20

考虑到字符串流的使用,你会怎么做呢,因为我想稍后使用这些数字?基本上如何根据字符串流使用char数组。

1 个答案:

答案 0 :(得分:0)

我认为语言是C,这是我认为你想要的代码:

#include <stdio.h>
#include <string.h>
#include <cstdlib>

const int N = 100000;

static char buffer[N]; //buffer to read the user input
static char Teams[N][40];
static char probFG[N][10];
static char probTD[N][10];

int main ()
{
    FILE *file = fopen("myFile.txt","r"); //open the file(i assume is a txt)
    int lineIndex = 0; //keep track of the current row

    //reading the file
    while(fscanf(file,"%s",buffer) != EOF) {
        int index = 0; //this int keep the track of the current column
        char * pch;
        pch = strtok (buffer,",");
        while (pch != NULL) { //split the string
            //printf("%s\n",pch);
            if(index == 0) 
                strcpy(Teams[lineIndex],pch);
            else if(index == 1)
                strcpy(probFG[lineIndex],pch);
            else
                strcpy(probTD[lineIndex],pch);
            pch = strtok (NULL, ",");

            index++;
        }

        lineIndex++;
    }

    //if you want to convert the char to float use this function
    //as an example here is the sum of the first two numbers in the first row
    double a = atof(probFG[0]);
    double b = atof(probTD[0]);

    double c = a + b;

    printf("%lf\n",c);

    return 0;
}

希望它有所帮助。