例如:我想在不使用(ctrl+d或按任何字符)的情况下终止输入,因为这样做会导致程序执行,第二个scanf()不起作用。我不允许输入数组中的元素数。
for(i=0;a[i]<10000;i++)
{
if(scanf("%d",&a[i])==1)
count++;
}
for(j=0;a[j]<10000;j++)
{
if(scanf("%d",&b[j])==1)
count1++;
}
您可以这样做:
for(i=0;a[i]<10000;i++)
{
// chack that input correct
if((scanf("%d",&a[i])==1)
{
count++;
}
else // if input is incorrect
{
// read first letter
int c = getchar();
if( c == 'q' )
{
break; // stop the loop
}
// clean the input buffer
while( getchar() != 'n' );
}
}
当您想停止输入时,只需输入字母q而不是数字
如果您想在scanf()
读取字符时退出第一个循环,那么您可以考虑使用getchar()读取整数。您可以在链接中为该函数添加一个额外条件,以便在输入特定字符时标记标志。
例如,如果你想在输入为X
时结束循环,你可以使用类似于的东西
int get_num()
{
int num = 0;
char c = getchar_unlocked();
while(!((c>='0' && c<='9') || c == 'X'))
c = getchar_unlocked();
if(c == 'X')
return 10001;
while(c>='0' && c<='9')
{
num = (num<<3) + (num<<1) + c -'0';
c = getchar_unlocked();
}
return num;
}
//------------//
for(i=0;;i++)
{
temp = get_num();
if(temp < 10000)
count++;
else
break;
}
for(j=0;;j++)
{
temp = get_num();
if(temp < 10000)
count1++;
else
break;
}