简体   繁体   English

如何退出“ do-while”循环?

[英]How to exit from a “do-while” loop?

I'd like to know what's the best way to exit from a do-while loop without using EOF or another number. 我想知道在不使用EOF或其他数字的情况下退出do-while循环的最佳方法是什么。
Is there a way to enter a character so that the user can exit the loop? 有没有一种方法可以输入字符,以便用户退出循环?
I've tried writing printf("Enter a number ('x' to exit): but it doesn't work. 我尝试编写printf("Enter a number ('x' to exit):但不起作用。
Do you know another method? 你知道另一种方法吗?
I can't use EOF because otherwise the program won't count -1 as a number and the number -1 will be used exclusively to exit the loop. 我不能使用EOF,因为否则程序将不会将-1视为一个数字,而数字-1将专门用于退出循环。

#include <stdio.h>

int even(int number);

int main(){
    int n;
    do{
        printf("Enter an integer (x to terminate): ");
        scanf("%d", &n);
        if(n=='x'){
            break;
        }
        printf("%d\n", even(n));
    }while(n!='x');
    return 0;
}

int even(int number){
    if(number%2==0){
        return 1;
    }else{
        return 0;
    }
}

Keep the return value from scanf() like in 保留scanf()的返回值,例如

 int scanreturn=0;
 /* ... */
 scanreturn= scanf("%d", &n);

Then use this as condition for the do-while 然后以此为条件

}while (scanreturn == 1);

This works because scanf() returns the number of successfully scanned input fields. 这是scanf()因为scanf()返回成功扫描的输入字段的数量。
That will be 1, as long as one integer was successfully scanned. 只要成功扫描了一个整数,该值为1。
When "x" is entered, or anything not looking like an integer, the loop will end. 当输入“ x”或任何看起来不像整数的东西时,循环将结束。

Compare https://en.cppreference.com/w/c/io/fscanf 比较https://en.cppreference.com/w/c/io/fscanf

Return value: 返回值:
Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned. 成功分配的接收参数的数量(如果在分配第一个接收参数之前发生匹配失败,则为零);如果在分配第一个接收参数之前发生输入失败,则为EOF。

Or quoting from C standard 7.21.6.4, eg http://port70.net/~nsz/c/c11/n1570.html#7.21.6.4 或引用C标准7.21.6.4,例如http://port70.net/~nsz/c/c11/n1570.html#7.21.6.4

... the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure. ... scanf函数返回分配的输入项的数量,如果早期匹配失败,该数量可能少于提供的数量,甚至为零。

int n, val=1;

do{
    printf("Enter an integer (x to terminate): ");
    val=scanf("%d", &n);
    printf("%d\n", even(n));
}while(val!=0);

Scanf() returns number of items successfully read. Scanf()返回成功读取的项目数。

You can do this too: 你也可以这样做:

int n;
char c[25];

do{
    printf("Enter an integer (x to terminate): ");
    scanf("%24s", c);
    printf("%d\n", even(atoi(c)));
}while(c[0]!='x');

You have a couple of ways to go with this. 您有两种方法可以解决此问题。

scanf returns the number of successful conversions and assignments. scanf返回成功的转换和分配的次数。 If you're expecting a single decimal integer input and the first thing you see is 'x' , then you have a matching failure , and scanf will return 0. So, you can do something like 如果期望输入一个十进制整数,并且看到的第一件事是'x' ,则说明匹配失败 ,并且scanf将返回0。因此,您可以执行类似的操作

printf( "Gimme a number: " );
if ( scanf( "%d", &n ) == 1 )
{
  // do something with n
}
else
{
  if ( !feof( stdin ) )
  {
    // user entered something that isn't a decimal digit
  }
  else
  {
    // EOF signaled on input stream (ctrl-D, ctrl-Z, EOF from redirected file, etc.).
  }
}

The problem is that this leaves unmatched input in the stream to foul up the next read. 问题在于,这会在流中留下无与伦比的输入,以阻塞下一次读取。 A better solution IMO is one that reads everything as text, then uses strtol to convert the text to an integer. IMO的一种更好的解决方案是将所有内容读取为文本,然后使用strtol将文本转换为整数。

#include <stdlib.h> // for strtol
#include <ctype.h>  // for isspace

#define MAX_INPUT_LENTH 13 // enough for 10 decimal digits plus sign plus newline plus string terminator

char input[MAX_INPUT_LENGTH+1];

printf( "Gimme a number: " );
if ( fgets( input, sizeof input, stdin ) )
{
  char *chk; // will point to first character in input that *isn't* a
             // decimal digit
  int tmp = strtod( input, &chk, 10 );
  if ( !isspace( *chk ) && *chk != 0 )
  {
    // input is not a valid decimal integer
  }
  else
  {
    n = tmp; // don't assign n until you know you have valid input
  }
}
else
{
  if ( feof( stdin ) )
  {
    // end-of-file signaled on input stream
  }
  else
  {
    // error during input
  }
}

Neither of these solutions are in a loop, but you should be able to figure out how to integrate them into a looping structure. 这些解决方案都不是循环的,但是您应该能够弄清楚如何将它们集成到循环结构中。

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

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