2016-06-11 38 views
2

問題:C程序空間分隔整數的輸入字符串轉換爲int數組

我想使一個C程序,需要空間分隔整數的一個字符串作爲輸入(正和負,可變數目數字)並將字符串轉換爲一個int數組。

還有一個關於從堆棧溢出字符串輸入數組讀取int的問題,但它不適用於數字長度超過1或負數的數字。

嘗試:

#include <stdio.h> 
int main() { 
    int arr[1000], length = 0, c; 
    while ((c = getchar()) != '\n') { 
    if (c != ' ') { 
     arr[length++] = c - '0'; 
    } 
    } 
    printf("["); 
    for (int i = 0; i < length-1; i++) { 
    printf("%d,", arr[i]); 
    } 
    printf("%d]\n", arr[length-1]); 
} 

如果我輸入以下到終端:

$ echo "21 7" | ./run 
$ [2,1,7] 

這是陣列I得到:[2,1,7]而非[21,7 ]

如果我輸入以下內容:

$ echo "-21 7" | ./run 
$ [-3,2,1,7] 

我得到:[-3,2,1,7]而不是[-21,7],這是沒有意義的。

但是,如果我輸入:

$ echo "1 2 3 4 5 6 7" | ./run 
$ [1,2,3,4,5,6,7] 

注:我假設輸入它總是空格隔開的整數的字符串。

+0

爲什麼'length'在使用前未初始化爲某個值? – babon

+0

我修正了這個問題。我注意到我正在使用'getchar',它每次掃描一個字符。 'scanf'在這裏有幫助嗎?但是這並不能解釋爲什麼我爲'-21'獲得'[-3,2,1]'。 – user6005857

+0

由於'-'的ASCII碼比'0'的ASCII碼小3,所以你得到'-3'。 getchar()只有一個字符,不管字符是什麼類型,所以你將減號視爲一個數字。 – Arc676

回答

3

完整的程序(改編自this answer by @onemasse)(不再需要無效的輸入停止讀取輸入):

#include <stdio.h> 
#include <stdlib.h> 

int main() { 
    int arr[1000], length = 0, c, bytesread; 
    char input[1000]; 
    fgets(input, sizeof(input), stdin); 
    char* input1 = input; 
    while (sscanf(input1, "%d%n", &c, &bytesread) > 0) { 
     arr[length++] = c; 
     input1 += bytesread; 
    } 
    printf("["); 
    for (int i = 0; i < length-1; i++) { 
     printf("%d,", arr[i]); 
    } 
    printf("%d]\n", arr[length-1]); 
    return 0; 
} 

scanf/sscanf手冊頁:

這些函數返回的數輸入項目分配。如果發生匹配失敗,這可能會少於規定的數量,甚至可能爲零。

因此,如果返回值爲0,則知道它無法再轉換。

樣品I/O:

$ ./parse 
1 2 3 10 11 12 -2 -3 -12 -124 
[1,2,3,10,11,12,-2,-3,-12,-124] 

注意:我目前不能確定究竟是如何工作的。我會仔細看看的。但是,如果有人瞭解,請編輯此帖子或發表評論。

+0

魔術發生在'sscanf()'調用中,它將一個指向'char *'字符串的指針作爲第一個參數。第二個參數表示你應該讀入一個整數到'c'並且讀入'bytesread'的字節數量。你使用'bytesread'來增加指針'input1'。這樣你改變你讀下一個整數的位置。 – onemasse

4

這是一個準系統版本(沒有錯誤檢查,尾隨空間應的數字後留下的),我相信你可以從這裏拾起:

int main(void) 
{ 
    int c; 
    int i, num = 0, neg = 0; 
    while ((c = getchar()) != EOF) { 
     if (c != ' ') { 
      if (c == '-') { 
       neg = 1; 
      } else { 
       i = c - '0'; 
       num = num * 10 + i; 
      } 
     } else { 
      (neg == 1) ? num *= -1 : num; 
      printf("%d\n", num + 2); // this is just to show that you indeed get an integer and addition works 
      num = 0; 
      neg = 0; 
     } 
    } 
} 
1

我沒有做很多C,但這裏是我的:)

#include"stdio.h" 
#include"string.h" 
#include"stdlib.h" 

#define CHUNK 1000000 

#define INT_COUNT 10000 


int main(void) { 
/*get all of the input*/ 
char temp_str[CHUNK] = ""; 
char* full_string = malloc(CHUNK * sizeof(char)); 
if (full_string == 0) { 
    printf("Memory Error\n"); 
    exit(1); 
} 
int count = 2; 
do { 
    fgets(temp_str, CHUNK, stdin); 
    strcat(full_string, temp_str); 
    full_string = realloc(full_string, count * CHUNK * sizeof(char)); 
    if (full_string == 0) { 
     printf("Memory Error\n"); 
     exit(1); 
    } 
    count++; 
} while (strlen(temp_str) == CHUNK - 1 && temp_str[CHUNK - 2] != '\n'); 

//parse the input 
char* token = strtok(full_string, " "); 

int* arr = malloc(INT_COUNT * sizeof(int)), length = 0; 
if (arr == 0) { 
    printf("Memory Error\n"); 
    exit(1); 
} 

count = 1; 

while (token != 0) { 
    arr[length] = atoi(token); 
    token = strtok(0, " "); 
    length++; 
    if (length == count * INT_COUNT) { 
     count++; 
     arr = realloc(arr, count * INT_COUNT); 
     if(arr == 0) { 
      printf("Memory Error\n"); 
      exit(1); 
     } 
    } 
} 

free(full_string); 

//print the integers 
for (int i = 0; i < length; i++) { 
    printf("%d ", arr[i]); 
    if (i % 20 == 0 && i != 0) { 
     printf("\n"); 
    } 
} 

free(arr); 

return 0; 
} 
1

編輯了一下。但是,還存在負面問題。我稍後再回頭看看。如果你稍微調整一下,我想可能會有效。你試試你的方式。我會嘗試我的。但後來。

#include <stdio.h> 
int main() { 
    int arr[1000]={0}, length = 0, c, i; 
    while (1) { 
    c = getchar(); 

if(c=='-') 
{ 
    //minus sign has problem yet. I ll come back once I have better soln. 
} 
else if(c==' ' || c=='\n') 
{ 
    length-=2; 
    arr[length]= arr[length]*10 + arr[length+1]; 
    length++; 
    if(c=='\n') 
    { 
     break; 
    } 
} 
else if (c != ' ') { 
    arr[length++] = c - '0'; 
    } 
} 
    printf("["); 
    for (i = 0; i < length-1; i++) { 
printf("%d,", arr[i]); 
    } 
    printf("%d]\n", arr[length-1]); 
} 
相關問題