所以基本上我有這樣的事情:我如何插入一個字符串到一個數組在C
char string[256];
printf("Insert text:");
,我想讀(scanf函數)文成陣,我將如何做到這一點。
所以基本上我有這樣的事情:我如何插入一個字符串到一個數組在C
char string[256];
printf("Insert text:");
,我想讀(scanf函數)文成陣,我將如何做到這一點。
如果你想要把一些文字在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
scanf("%s", string);
或更正確..
scanf("%255s", string);
%s將讀取一個字符串,255將字符串長度限制爲255個字符,爲空字符串終止符留下至少一個空格。
它可以通過使用
功能
看到下面的程序,其採用的scanf()讀取簡單地完成兩串
http://www.csnotes32.com/2014/08/c-function-to-compare-two-strings.html
這是一個基本的東西,每本書或教程都應該告訴你。 – 2014-10-19 06:01:02