在 C 中有什么方法可以在没有 ctrl+d 的情况下终止数组中的 scanf() 输入?
Is there any way in C to terminate scanf() inputting in array without ctrl+d?
例如:我想在不使用(ctrl+d 或按任何字符)的情况下终止输入,因为这样做会导致程序执行并且第二个 scanf() 不会 work.I 不允许输入数组中的元素数。
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++;
}
如果你想在 scanf()
读取一个字符时跳出第一个循环,那么你可以考虑使用 getchar() 读取整数。您可以在 link 中为该函数添加一个额外的条件,以便在输入某个特定字符时标记一个标志。
例如,如果你想在输入为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;
}
你可以这样做:
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 而不是数字
例如:我想在不使用(ctrl+d 或按任何字符)的情况下终止输入,因为这样做会导致程序执行并且第二个 scanf() 不会 work.I 不允许输入数组中的元素数。
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++;
}
如果你想在 scanf()
读取一个字符时跳出第一个循环,那么你可以考虑使用 getchar() 读取整数。您可以在 link 中为该函数添加一个额外的条件,以便在输入某个特定字符时标记一个标志。
例如,如果你想在输入为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;
}
你可以这样做:
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 而不是数字