【问题标题】:Is there any way in C to terminate scanf() inputting in array without ctrl+d?C中是否有任何方法可以终止scanf()在没有ctrl + d的情况下输入数组?
【发布时间】:2015-05-01 04:09:48
【问题描述】:

例如:我想在不使用(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++;
 }

【问题讨论】:

  • 除了输入 20,000 个数字之外,“不使用 ... any 字符”很难结束输入。当然必须允许用户输入一些字符才能提前结束输入。如果不允许用户输入任何字符,请使用ReadMyMind() 函数。

标签: c arrays input scanf


【解决方案1】:

你可以这样做:

 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 而不是数字

【讨论】:

  • 好的。但是 else 下的第一条语句应该是 char c=getchar();
【解决方案2】:

如果您想在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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2018-08-06
    • 2018-02-23
    相关资源
    最近更新 更多