c - 如何将字符串插入到c中的数组中

标签 c arrays string scanf

所以基本上我有这样的东西:

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/

相关文章:

java - java中如何找到两个相似的字符串?

java - RadioButton.setChecked() 似乎不起作用

c - C语言中数组长度有限制吗?

c - fgets() 进入从 stdin 读取的无限循环

java - 如何将 List<List<String>> 转换为 String[][]?

java - 将颜色添加到颜色数组

java - Java 中 findInLine 方法中的字符串模式

c - C 中的 Linux 定时器

c - 错误的值 - 将大字符分解为 int 数组

c# - 在 C# 中将数字数组转换为字节,反之亦然