使用 gdb 调试时的字符/字符串输入

标签 c gdb

我的程序包含 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;
               }

调试画面: enter image description here

最佳答案

您的 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;
}

关于使用 gdb 调试时的字符/字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50358111/

相关文章:

c - 为什么 "double"表示为整数?

c - 在 COM 嵌入式 IE 中设置 Accept-Language

gdb - 为什么 cortex-m3 会在 gdb 中重置为地址 0?

java - 如何在Java中处理C字符数组

c++ - 数组在通过引用传递给函数之前和之后显示不同的地址

gdb - 如何在带有参数的可执行文件上运行 gdb?

macos - 在 Mac 上没有对 gdb 的 TUI 支持?

GDB - 附加和中断正在运行的 Go 应用程序

c++ - unsigned int 和 double 转换顺序

c - 在c中使用堆栈和指针