【问题标题】:Storing element in string将元素存储在字符串中
【发布时间】:2017-10-20 10:12:03
【问题描述】:

问题:在我的代码中,无论我为 n 输入什么,编译器都只允许我输入和输出其中的一半。为什么?

#include<stdio.h> 
#include<stdlib.h> 
int main()
{   
    int n; 
    scanf("%d\n",&n);   
    char *c= (char*)malloc((n+1)*sizeof(char));
    c[n]='\0';
    for(int i=0;i<n;i++)
    { 
        scanf("%c",&c[i]);
    }
    for(int i=0;i<n;i++)
    {
        printf("%c",c[i]);
    }
}

【问题讨论】:

  • 不要按一次输入一个字符,而是连续输入。
  • 记住:Enter ('\n') 也是一个字符!

标签: c string loops io scanf


【解决方案1】:

改变这个:

scanf("%c",&c[i]);

到这里:

scanf(" %c",&c[i]);

样本输出:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
5
a
b
c
d
e
abcde

我在Caution when reading char with scanf (C) 中讨论了这个解决方案背后的原因。


PS:Do I cast the result of malloc?不!

另外,既然你是动态分配内存的,别忘了在main()末尾加上free(),就像这样:

free(c);

【讨论】:

    【解决方案2】:

    问题。编译器只允许你输入数组大小的一半,为什么?

    问题原因:

    scanf("%c",&c[i])          //Here %c takes enter key also as a part of input which reduces the input size to half.
    

    因此,您的问题主要有两种解决方案:

    溶胶。 1 => 只需要包含空格,其余代码相同。

    scanf(" %c",c[i]) //use whitespace before %c

    溶胶。 2 => 不要一次输入一个字符,请一次性输入整个输入,然后按回车键。

    【讨论】:

    • @ankit 如果您发现任何答案对您有用并且也有助于理解您的问题..那么您应该接受那个答案,以便社区知道该问题的解决方案.. :)跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多