2014-02-18 200 views
0

如何讀取具有字符串和雙倍逗號的輸入文件,並用逗號分隔多行。我想保留在一個二維數組中的字符串,如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數組。

+0

你在用什麼語言? – Virtlink

+0

@Virtlink我猜C因爲strtok標籤 – emcas88

回答

0

嗯,我asume語言爲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; 
} 

希望它能幫助。

+0

如果你認爲我的回答是正確的請接受它,有任何疑問你可以問我 – emcas88