如果输入文件中的字符串和双字符用多行逗号分隔,我该如何读取。我想将字符串保存在像char Teams[5][40]这样的二维数组中。我想对每一行数字执行相同的操作。所以对于第二行的数字,我需要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数组。
发布于 2014-02-19 02:52:39
好吧,我假设语言是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;
}希望能有所帮助。
https://stackoverflow.com/questions/21861737
复制相似问题