【问题标题】:character/string input while debugging using gdb使用 gdb 调试时的字符/字符串输入
【发布时间】:2023-03-31 12:00:01
【问题描述】:

我的程序包含 character 的输入代码,但在调试过程中没有考虑它。

它考虑其他数据类型(int、float 等)的输入

程序:

               #include<stdio.h>
               int main()
                 {
                    int n,i=0;
                    char c;                               
                    scanf("%d",&n);
                    int a[20];
                    while(1)
                        {
                           scanf("%c",&c);
                           if(c=='\n')
                           break;
                           else
                             {
                                if(c!=32)
                                a[i++]=c-48;
                             }

                        }
                   for(i=0;i<10;i++)
                   printf("%d ",a[i]);

                    return 0;
               }

调试屏幕:

【问题讨论】:

  • 我建议 scanf("%c",&amp;c); 应该是 scanf(" %c",&amp;c); 加上一个空格来清除前导空格。请参阅 scanf() leaves the newline char in buffer? 大多数格式说明符,如 %d%f 会过滤掉前导空格,但 %c 不会,除非你用空格指示它。
  • 旁白:c-48 暗示有 ASCII 编码,你想提取一个数字,在这种情况下,c - '0' 既清晰又便携。
  • @user3121023 是的,但这可能会使一行中输入的多个字符混淆,可能会有多个空格分隔。 " %c" 干净可靠。
  • @user3121023 我不明白你的“换行符”的概念。 scanf 的数据可以全部输入一行。如果你想要一个空行来停止输入,我建议像往常一样使用fgets
  • @user3121023 我明白了,first %c 条目将在循环之前的 %d 条目之后拾取换行符。

标签: c gdb


【解决方案1】:

您的scanf("%d",...) 在缓冲区中留下一个换行符,随后的scanf("%c",...) 会立即使用该换行符。为了克服这个问题,在scanf("%d",...) 之后只让一个scanf 占用空格:

int main()
{
    int n,i=0;
    scanf("%d",&n);

    int a[20];
    char c=0;
    scanf(" %c",&c);  // Consume white spaces including new line character before the value for c.
    while(c!='\n' && i < 20)
    {
        if(c!=32) {
            a[i++]=c-'0';
        }
        scanf("%c",&c);
    }
    for(int x=0;x<i;x++)
        printf("%d ",a[x]);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多