2015-03-31 22 views
0

我與值txt文件:複製值成整數

1 -200 3 4

如何獲得的長度輸入(以便我可以告訴代碼在哪裏停止)並在空白之前複製值?即我想A = 1,B = -200,C = 3,d = 4(我已嘗試的方法中似乎只是在形式添加值:-2 + 0 + 0 = -2)

的代碼我工作:

char buffer[100]; 
char c; 
int x = 0; 
while (fgets(buffer, sizeof(buffer), stdin) != NULL){ // while stdin isn't empty 
    for (int i = 0; i < 10; i++){ // loop through integer i (need to change 
            //i < 10 to be size of the line) 
     if (strchr(buffer, c) != NULL){ 
     // if there is a white space 
     // add the value of buffer to x 
      x += buffer[i] - '0'; 
     } 
    } 
    } 

回答

0

試試這個,它並沒有增加4個數字的約束:

char buffer[100], 
char bufferB[100]; //holds the individual numbers 
int x = 0, i = 0, j = 0; 
//you dont need a while in fgets, because it will never be NULL (the '\n' will always be read) 
if (fgets(buffer, sizeof(buffer), stdin) != NULL){ 
    while(buffer[i] != '\n' && buffer[i] != '\0'){ 
     //If we have not occured the white space store the character 
     if(buffer[i] != ' '){ 
      bufferB[j] = buffer[i]; 

      j++; 
     } 
     else{ //we have found the white space so now make the string to an int and add to x 
      bufferB[j] = '\0'; //make it a string 

      x += atoi(bufferB); 

      j = 0; 
     } 

     i++; 
    } 

    //The last number 
    if(j != 0){ 
     bufferB[j] = '\0'; 

     x += atoi(bufferB); 
    } 
} 
+0

輝煌!雖然有些令人困惑,但希望通過測試和打印聲明,我可以找出背後的步驟。 謝謝! – 2015-03-31 03:23:01

+0

該代碼只讀取一行;原始代碼讀取多行。我認爲'while(fgets(buffer,sizeof(buffer),stdin)!= NULL)'循環是適當的。 – 2015-03-31 04:04:27