2010-11-02 181 views
1

在我的代碼中,我試圖忽略新行。有沒有更好的方法來做到這一點?如何在沒有 n的情況下獲得角色?

 do 
     { 
      scanf("%c",&wouldCount); 
     } while(wouldCount == '\n'); 

原代碼

#include <stdio.h> 

int main() 
{ 
    char Yes = 'Y'; 
    char wouldCount; 
    int counter; 
    int start; 
    int end; 
    int increment; 
    const END_DEFAULT = 1; 
    const INCREMENT_DEFAULT = 1; 
    printf("Would you like to count?"); 
    scanf("%c",&wouldCount); 
    while(wouldCount == 'Y' || wouldCount == 'y') 
    { 
     printf("Please enter start number."); 
     scanf("%d",&start); 
     printf("Please enter a number you would like to stop at?"); 
     scanf("%d",&end); 
     printf("Please enter a number to increment by."); 
     scanf("%d",&increment); 
     if(end < start) 
     { 
      end = start + END_DEFAULT; 
     } 
     if(increment <= 0) 
     { 
      increment = INCREMENT_DEFAULT; 
     } 
     for(counter = start; counter < end; counter += increment) 
     { 
      printf("%d\n",counter); 
     } 
     printf("Would you like to count?"); 
     do 
     { 
      scanf("%c",&wouldCount); 
     } while(wouldCount == '\n'); 
    } 
return 0;  
} 
+1

我不明白你的意思。是否需要忽略換行符? – Jim 2010-11-02 02:49:29

+0

當我在運行程序時按Enter鍵時,我不希望它退出。 – user494243 2010-11-02 02:55:30

回答

3

你可以改變的scanf( 「%C」,& wouldCount);到scanf(「\ n%c」,& wouldCount);以及放棄do/while循環。這將告訴scanf忽略沒有輸入字符的輸入。

請參閱scanf c++ reference

相關問題