2017-08-17 22 views
0

我試圖從包含2013/2014英格蘭超級聯賽賽季每個燈具統計數據的CSV文件中獲取數據。我正在嘗試採用對我有效的數據,以便我可以根據燈具的結果創建最終的聯賽表格。下面是從文件的兩行看起來像:將指針中的每個其他值拆分爲兩個單獨的標識符c

2013年8月17日,阿森納,阿斯頓維拉,1-3,1-1

2013年8月25日,加的夫,曼城, 3-2,0-0

正如你所看到的「2013-08-17」和「2013-08-25」在索引0,「阿森納」和「加的夫」在索引1等。我正在使用索引1到4來幫助製作我的表格,並且已經開始在逗號分隔每個索引,以便它們打印出如此:

阿森納

維拉

1-3

1-1

我已經到tokenise索引3和4在連字符(即 「1-3」 和「1-1」在上述例子中),以便每個數字打印出在這樣一個單獨的行:

H:1

H:1

F:1

F:3

與數字 「H:」 在前面的是在相同的指針,並用數字 「F:」 在前面都在另一個指針中,但我需要H中的兩個數字:分別標識符和F中數字相同,並且需要爲每個燈具完成。我一直在努力做到這一點,並想知道是否有人可以幫忙?!這裏是我的功能在我tokenising我的數據,所以你可以看到發生了什麼事情:

void tokenise(char *line)//the pointer line holds each line as the file as it is read in 
{ 
    char homeTeam[32]; 
    char awayTeam[32]; 
    char fullScore[12]; 
    char halfTimeScore[12]; 


    char *token = strtok(line, ",");//the pointer *token is given the lines to hold 
    int i = 0; 

    while(token != NULL) 
    { 
     switch(i) 
     { 
      case 1: 
       strcpy(homeTeam, token);//splitting indexes up at comma 
       break; 

      case 2: 
       strcpy(awayTeam, token); 
       break; 

      case 3: 
       strcpy(fullScore, token); 
       break; 


      case 4: 
       strcpy(halfTimeScore, token); 
       break; 

      default: 
       printf(""); 


     } 

     i++; 
     token = strtok(NULL, ","); 



    } 


    char *halfTimeScoreToken = strtok(halfTimeScore, "-");//*halfTimeScoreToken is the pointer that holds the numbers with "H:" in front 

    while(halfTimeScoreToken != NULL) 
    { 
     printf("\nH:%s", halfTimeScoreToken); 
     halfTimeScoreToken = strtok(NULL, "-"); 

    } 

    char *fullScoreToken = strtok(fullScore, "-");//*fullScoreToken is the pointer that holds the numbers with "F:" in front 

    while(fullScoreToken != NULL) 
    { 
     printf("F:%s\n", fullScoreToken); 
     fullScoreToken = strtok(NULL, "-"); 

    } 



} 
+0

「* struggling *」具有「*分離*」變量(您似乎稱之爲「*標識符*」)或「*掙扎*」爲「*每個燈具*」做這個操作? – alk

+0

對於編程還不是很瞭解,但對於編程還是相當新穎的,抱歉!我正在努力將每個其他數字放入單獨的變量中。 – Aaron

+0

忽略代碼,你是如何得到1-3和1-1(依次)變成H:1,H:1,F:1,F:3(按照這個順序)。邏輯在哪裏? – Lundin

回答

0

假設char *score分的得分像"1-3",則:

int i1= atoi(score); 
while (*score!='-') score++; 
score++; 
int i2= atoi(score); 

這也被稱爲愚蠢的字符處理。

更完整的示例將是:

if (!isdigit(*score)) return(-1); 
int i1= atoi(score); 
while (*score && *score!='-') score++; 
if (!*score) return(-1); 
score++; 
if (!isdigit(*score)) return(-1); 
int i2= atoi(score); 

其中return(-1)意味着一個錯誤。

+0

如果字符串沒有containt'-'你會訪問邊界以外。[爲什麼不應該使用atoi()?](https://stackoverflow.com/questions/17710018 /爲什麼 - 不應該,我使用-的atoi) –

相關問題