簡體   English   中英

如何在C語言中使用字符退出循環?

[英]How to use a character to quit a loop in c Language?

如何使用q作為字符退出? 如何使用q退出此代碼。 循環直到獲得q的ASCII值。 `

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int pos=0,neg=0,zero=0,i=0,num;
  printf("Input numbers.");
  scanf("%d",&num);
  for(i=0;num!="q";i++)
  {

      if(num>0)
      {
          pos++;
      }
      if(num<0)
      {
          neg++;
      }
      if(num==0)
      {
          zero++;
      }
  }
  printf("You entered \n\tpositive number::: %d times\nNegative number:::%d times\nZero:::%d times",pos,neg,zero);


}

`

您應該在循環內移動scanf行。

for(i=0;num!="q";i++)
{
  scanf("%d",&num);
  ...
scanf("%d",&num);      /*     <-- for initializing num before using    */
for(i=0;num!='q';i++)  /*     <-- compare with 'q' and not with "q"    */
{
     scanf("%d",&num); /*     <-- take input                           */
     //your code 
}

Comapare使用'q'字符 )而不是字符串文字"q" ,它比較'q''\\0'請注意單引號 )。

另外,您還需要在循環內接受輸入, 否則 num 在循環內不會更改

嘗試更改為while並將scanf放入循環內。

scanf("%d",&num);
while(num!="q")
{
    if(num>0)
    {
        pos++;
    }
    if(num<0)
    {
        neg++;
    }
    if(num==0)
    {
        zero++;
    }
    scanf("%d",&num);
}

首先,您實際上應該循環:

while(1) { // infinite loop
 ...
}

...然后在循環內掃描整數:

while(1) { // infinite loop
 scanf("%d",&num)
 ...
};

...然后記住,哎呀,用戶可以輸入不是數字的“ q”

while(1) { // infinite loop
 char input[100];
 scanf("%s", input);
 if( strcmp( input, "q" ) == 0 ) {
     break;
 }
 else {
    sscanf( input, "%d", &num); 
 }
 ...
}

...然后添加您的測試

   while(1) { // infinite loop
     char input[100];
     scanf("%s", input);
     if( strcmp( input, "q" ) == 0 ) {
         break;
     }
     else {
        sscanf( input, "%d", &num); 
     }

     if(num>0) {
        pos++;
     }
     if(num<0) {
        neg++;
     }
     if(num==0) {
        zero++;
     }
   }

我會這樣:

int fldCnt = scanf("%d", &num);
while (fldCnt == 1)
{
    // your code
    fldCnt = scanf("%d", &num);
}

輸入“ q”時,零字段將轉換為%d

#include <stdio.h>

int main(void){
    int pos=0, neg=0, zero=0;
    int i, ch, num;

    printf("Input numbers.\n");
    do {
        while(1 == scanf("%d", &num)){//input into inside loop
            if(num > 0)
                pos++;
            else if(num < 0)
                neg++;
            else //if(num==0)
                zero++;
        }
        ch = getchar();//q not allow `scanf("%d", &num)`
    } while(ch != 'q' && ch != EOF);
    printf("You entered \n\tpositive number:::%d times\n\tNegative number:::%d times\n\tZero:::%d times\n",pos,neg,zero);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM