所以基本上我有这样的东西:
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
关于c - 如何将字符串插入到c中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26447788/