【问题标题】:scanf store newline as the first element of the arrayscanf 将换行符存储为数组的第一个元素
【发布时间】:2013-07-15 07:48:57
【问题描述】:

您好,我有一个关于将数据输入数组的问题

为什么 scanf 将'\n' 存储到这段代码中数组的第一个元素中?

#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int main (void)
{
    // Global declarations
       int str_length;
       char str[MAX];
       int count;
       char temp;
    // Statements

       // prompt user for string length
       printf("Enter string length: ");
       scanf("%d", &str_length);

       printf("Enter string: ");
       // input string
       for(count = 0; count < str_length; count++)
       {
            scanf("%c", &str[count]);
            printf("%c", str[count]);
       }

       for(count = 0; count < str_length; count++)
       {    
            temp = str[0]; // set temp to the first element
            str[count] = str[count+1]; // set the next element to be the first element
            str[str_length-1] = temp;  // swap the first element and the last element
            puts(str);
       }


    system("PAUSE");
    return 0;
}

当我在数组中输入 1234567890 而不是 1 作为第一个元素时,第一个元素是换行符 '\n'

提前感谢您的帮助。

【问题讨论】:

    标签: arrays newline scanf


    【解决方案1】:

    因为当你到达这里时

    scanf("%d", &str_length);
    

    然后用户键入类似 4 的内容然后回车,您的缓冲区将充满4\n。 4 转到 str_length\n 留在缓冲区。 所以你需要清理缓冲区,只需添加:

    fflush (stdin);
    

    注意,当清除char str[MAX] 并且用户在其中输入字符时,您需要在字符串的末尾添加空终止符。 只需添加

    str[str_length] = '\0';
    

    【讨论】:

      【解决方案2】:

      在得到行的长度后,您似乎没有消耗 \n

        // prompt user for string length
         printf("Enter string length: ");
         scanf("%d", &str_length);
      

      您需要做的就是在这一行之后添加一个 %c 的 scanf 并将其丢弃。

      【讨论】:

      • 你所说的 \n 是什么意思?您能否详细解释一下,因为我真的很想知道 printf 没有消耗 \n 的原因。非常感谢
      • scanf 从标准输入读取,您在其中输入一个数字,后跟 \n。 %d 的 scanf 不会消耗尾随的 \n。你需要把它吃掉然后扔掉。
      猜你喜欢
      • 2018-07-12
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      相关资源
      最近更新 更多