2017-06-15 58 views
-3

我有一個文本文件,它看起來像這樣掃描的整數:無法從文本文件

coordinate  size average Intensity 
==========  ==== ================= 
(187,18)  31  217.8 
(58,29)   34  212.1 
(124,71) 47 216.1 
(245,71) 32 197.8 
(96,113) 30 191.6 
(244,135) 33 199.6 

我試着只接收「大小」的變量,但由於某種原因,我不是能這樣做。這是我試過的代碼:

FILE * textofGags; 
int xx;  
fopen_s(&textOfGags,"dust.txt","rt"); 
fseek(textOfGags,0L,SEEK_SET); 
fscanf_s(textOfGags,"%*[^\n]\n,",NULL); 
fscanf_s(textOfGags,"%*[^\n]\n,",NULL); 
while(fscanf_s(textOfGags,"%d",&xx)==1){ 
    printf("%d",xx); 
    fscanf_s(textOfGags,"%*[^\n]\n,",NULL); 
} 

現在我只是試圖以打印,看看問題出在哪裏,但似乎我甚至不能接受的數字。有人能指出我的錯誤嗎?

+0

我想你忘記了C +,C,C {}和C## – Stargateur

+0

C/C++也總是充滿樂趣。而我的首選語言:Brainfuck永遠不會錯過。 – Olaf

+0

@Olaf或者至少malbolge :-P –

回答

2

我想你有一些downvotes錯誤的標籤:-) 無論如何,我認爲我們應該互相幫助。

該代碼對我來說看起來有點複雜,即使有調試器,也可能很難確定fscanf("%*[^\n]\n," ...是否將文件位置實際移動到正確的位置;

我建議逐行讀入文件,然後根據其特定內容分析每一行,並讀取大小。例如,可能會使用這樣一個事實,即大小值是關閉後的第一個整數值')',而沒有這樣的')'的行可能會被忽略。

希望它可以幫助:-)

int main() { 

    FILE * textofGags; 
    int xx; 
    textofGags = fopen("dust.txt","rt"); 
    if (textofGags) { 
     char line[1000]; 
     while (fgets(line,1000,textofGags)) { 

      char *closingBrace = strchr(line, ')'); 
      if (!closingBrace) 
       continue; 

      closingBrace++; // first char after the ')' 
      if (sscanf(closingBrace,"%d",&xx) == 1) { 
       printf("size: %d \n", xx); 
      } 
     } 
    } 
}