2014-10-19 32 views
-4

所以基本上我有這樣的事情:我如何插入一個字符串到一個數組在C

char string[256]; 
printf("Insert text:"); 

,我想讀(scanf函數)文成陣,我將如何做到這一點。

+0

這是一個基本的東西,每本書或教程都應該告訴你。 – 2014-10-19 06:01:02

回答

2

如果你想要把一些文字在string變量,你可以使用:

1)fgets() - >fgets(string,256,stdin);

2)scanf() - >scanf(" %255s",string);

通過使用fgets,一個可以輸入包含空格的字符串。

但是通過使用scanf不能輸入包含空格的字符串。


例如:

#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char string[256]; 
    char *p; 
    printf("Insert text:"); 
    fgets(string,256,stdin); 
    //Remove \n from string 
    if ((p=strchr(string, '\n')) != NULL) 
     *p = '\0'; 
    printf("The string using fgets: %s\n",string); 
    printf("Insert text again:"); 
    scanf(" %255s",string); 
    printf("The string using scanf: %s\n",string); 
    return 0; 
} 

輸出

Insert text:hello world 
The string using fgets: hello world 
Insert text again:hello world 
The string using scanf: hello 
1
scanf("%s", string); 

或更正確..

scanf("%255s", string); 

%s將讀取一個字符串,255將字符串長度限制爲255個字符,爲空字符串終止符留下至少一個空格。

相關問題