[英]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", ÷r);
printf("it got here ");
printf("%c", divider);
使用以上代碼,我仍然設法到達了最后一行,就我個人而言,我認為scanf()
中的錯誤空間較小。
希望可以幫助您解決問題。
您是否在某個地方初始化了變量除法器? 嘗試將最后兩行替換為:
char divider;
divider = getchar();
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.