2016-03-01 86 views
3

我已經用C編寫了這個代碼。我需要解決一個問題,並且在那裏我需要輸入包含空格的5行字符串。這個程序將給我輸出所有5行字符串,包括空格。通過空格,我的意思是在輸入之前,我可以在空格之前和char或任何char之後放置空格。這就是爲什麼我寫了這段代碼,但我不明白爲什麼它不起作用。Scanf(「%[^ n]」)在循環內不能處理數組字符

#include<stdio.h> 
int main() { 
    char str[5][100]; 
    for(int i=0;i<5;i++) { 
     scanf("%[^n\]",str[i]); 
    } 
    for(int j=0;j<5;j++) { 
     printf("%s\n",str[j]); 
    } 
    return 0; 
} 

我想只有

scanf("%s",str[i]); 

使用,但那麼它忽視了裏面輸入的所有空格和修整的輸出。此外,我試圖使用

scanf(" %[^\n]",str[i]); 

這一次稍微好一點,但它忽略任何字符之前的所有空白空間示例輸入是。

Robin Islam 
// output showing 
Robin Islam 
// should show 
    Robin Islam 

我只想讓這個計劃,讓每個我的意思是輸出應顯示與輸入相同,不能忽視空間空白。有人請幫助我。嘗試了很多方法的,但不知道如何使它工作以及如何......請幫助

感謝, 羅賓

+0

scanf函數%s的讀取,直到字符串的結尾。你必須以其他方式分割空間。 – BitWhistler

+0

嘗試使用'scanf(「%99 [^ \ n] \ n」,str [i]);'。 – ddz

+0

'scanf()'不能很好的讀取行,使用'fgets()'。 – chux

回答

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

int main() { 

    char str[5][100]; 
    for(int i=0;i<5;i++) { 
     fgets(str[i],100,stdin); 
    } 
    for(int j=0;j<5;j++) { 
     printf("%s\n",str[j]); 
    } 

    return 0; 
} 
+0

好地方!謝謝。 – JCollerton

+0

非常感謝這幾乎是我需要解決我目前的問題,但一個問題。 當它在那裏打印結果時,我可以看到它增加了更多的換行符「\ n」,請告訴我爲什麼這樣。 –

+0

:)接受非常感謝。 –

2

scanf是千瘡百孔,只是search for it here,你會看到。應儘可能避免。

您正在閱讀整行內容,並且有這樣做的功能。 fgetsgetline。我更喜歡getline,因爲它爲您處理內存分配,不會有輸入超出緩衝區的風險。

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

int main() { 
    char *line = NULL; 
    char *lines[5]; 
    size_t linecap = 0; 

    for(int i = 0; i < 5; i++) { 
     /* Getline will allocate sufficient memory to line. 
      It will also reuse line, so... */ 
     getline(&line, &linecap, stdin); 

     /* ...we have to copy the line */ 
     lines[i] = strdup(line); 
    } 

    /* line must be freed after calls to getline() are finished */ 
    free(line); 

    for(int i = 0; i < 5; i++) { 
     printf("%s\n", lines[i]); 
    } 

    /* Cleaning up all memory is a good habit to get into. 
     And it removes clutter from you Valgrind report. */ 
    for(int i = 0; i < 5; i++) { 
     free(lines[i]); 
    } 

    return 0; 
} 
+1

爲了完整性,需要'free(lines [i])'。 – chux

+0

SCANF沒有錯,它是錯誤的使用。 – Michi

+0

@Michi [有很多方法可以使用'scanf'錯誤](https://stackoverflow.com/search?q=scanf)。除非你知道你在做什麼,否則最好避免。即使那樣,也許最好單獨做IO,並使用'sscanf'來代替。 – Schwern