首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用逗号分隔信息的输入文件

用逗号分隔信息的输入文件
EN

Stack Overflow用户
提问于 2014-02-19 01:57:50
回答 1查看 28关注 0票数 1

如果输入文件中的字符串和双字符用多行逗号分隔,我该如何读取。我想将字符串保存在像char Teams[5][40]这样的二维数组中。我想对每一行数字执行相同的操作。所以对于第二行的数字,我需要char probFG[5][10],第三行的数字是probTD [5][10]

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

代码语言:javascript
复制
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数组。

EN

回答 1

Stack Overflow用户

发布于 2014-02-19 02:52:39

好吧,我假设语言是C,下面是你想要的代码:

代码语言:javascript
复制
#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;
}

希望能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21861737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档