【问题标题】:how do i insert a string into an array in c如何在c中将字符串插入数组
【发布时间】:2014-10-19 05:56:57
【问题描述】:

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

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

并且我想将文本读入(scanf)到数组中,我将如何完成此操作。

【问题讨论】:

  • 这是一个基本的东西,每本书或教程都应该告诉你。

标签: c arrays string scanf


【解决方案1】:

如果您想在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

【讨论】:

    【解决方案2】:
    scanf("%s", string);
    

    或者更正确..

    scanf("%255s", string);
    

    %s 将读取一个字符串,255 将字符串长度限制为 255 个字符,为空字符串终止符留出至少一个空格。

    【讨论】:

      【解决方案3】:

      这可以简单地使用任何一个来完成

      1. scanf() 或
      2. gets()

      功能

      请看下面使用 scanf() 读取两个字符串的程序

      http://www.csnotes32.com/2014/08/c-function-to-compare-two-strings.html

      【讨论】:

        猜你喜欢
        • 2020-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多