繁体   English   中英

基本的C程序在函数中的最后scanf之后不会继续,scanf只是不断地接受输入

[英]Basic c program doesn't continue after the final scanf in the function, scanf just keeps accepting input endlessly

这是相关代码:

我对c语言世界有些陌生,所以请帮助我,问题出在代码底部: divider = getchar()divider = getchar()代码使程序陷于瘫痪,此后再也没有进展。 它只是允许输入的无限循环。 怎么了。 请具体说明,因为我对复杂概念并不完全熟悉(尽管无论解决方案多么复杂,我都渴望解决此问题)

void read_in(int n, int m)
{

    int a = 0, b = 0, i = 0, x;

    while (a != n && b != m)
    {
        if (b == 0 && i == 0)
        {
            printf("\nEnter row %d:  ", a);

         }

         scanf("%d", &array[a][b]);

         diglength[a][b] = floor (log10 (abs (array[a][b]))) + 1;

         if (b == m - 1)
         {
             a++;            
             b = -1;
         }
         if (b == -1 && i != 0 && a != n)
         {
             printf("\nEnter row %d:  ", a);
         }

         i++;
         b++;
    }

    printf("\nEnter the number of new lines in between rows: ");
    scanf("%d", &newlines);
    printf("\nEnter the span of each array element: ");

    scanf("%d", &span);

    check_span(n, m);
    getchar();
    printf("\nEnter the type of justification (l - left   r - right): ");

    just = getchar();

    while (just != 'r' && just != 'l')
    {
        printf("\nInvalid argument");
        printf("\nEnter the type of justification (l - left   r - right): ");
        scanf(" %c", &just);
    }

    printf("\nEnter the character to be placed in between elements: ");
    getchar();
    divider = getchar();
//THE PROGRAM NEVER GETS PAST HERE IT GETS STUCK ON THE ABOVE CHARACTER ASSIGNMENT...WHY

    printf("it got here "); printf("%c", divider);    
}

我使用Xcode对此进行了测试,并且由于您没有提供所有代码,因此我不得不跳过很多代码并测试了以下内容:

#include <stdio.h>

void read_in(int n, int m)
{ 
    char just = getchar();
    char divider;

    while (just != 'r' && just != 'l')
    {
        printf("\nInvalid argument");
        printf("\nEnter the type of justification (l - left   r - right): ");
        scanf(" %c", &just);
    }

    printf("\nEnter the character to be placed in between elements: ");
    getchar();
    divider = getchar();


    printf("it got here "); printf("%c", divider);    
}

int main(int argc, const char * argv[]) {

    read_in(8, 9);
    return 0;
}

并得到以下输出:

Invalid argument
Enter the type of justification (l - left   r - right): l

Enter the character to be placed in between elements: k
it got here k

我怀疑此函数或您发布的代码段之外可能有问题。

在其他新闻中,我发现scanf()可能令人困惑。 我选择将格式保留在我的数据库中,如下所示: scanf("%c", &foo)然后使用purge(stdin)从“ fresh”启动输入缓冲区。

printf("Enter the character to be placed in between elements: ");

fpurge(stdin);
scanf("%c", &divider);

printf("it got here ");
printf("%c", divider);

使用以上代码,我仍然设法到达了最后一行,就我个人而言,我认为scanf()中的错误空间较小。

希望可以帮助您解决问题。

您是否在某个地方初始化了变量除法器? 尝试将最后两行替换为:

char divider;
divider = getchar();

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM