2017-02-23 30 views
-2

我正在爲一個班級製作一個小型辦公桌費用計劃。我想包括一個循環。但是,每當我到達程序結束並將其循環回到開始時,它都會跳過我要求客戶名稱的部分,並將其留空。任何想法如何解決它?爲什麼在循環內部不重置字符串?

這裏是我的代碼:

#include <iostream>   // needed for Cin and Cout 
#include <string>    // needed for the String class 
#include <math.h>    // math functions 
#include <stdlib.h>    
using namespace std; 

#define baseCost 200.00 
#define drawerPrice 30.00 

int main(void) 
{ 
    while(true) 
    { 
     string cname; 
     char ch; 

     cout << "What is your name?\n"; 
     getline(cin, cname); 

     cout << cname; 

     cout << "\nWould you like to do another? (y/n)\n"; 
     cin >> ch; 

     if (ch == 'y' || ch == 'Y') 
      continue; 
     else 
      exit(1); 
    } 

    return 0; 
} 
+2

你有一個while循環圍繞main?這甚至編譯? >。< – OMGtechy

+0

由於您已經發現問題出在循環和字符串上,您是否可以將代碼簡化爲這樣?這讓每個人都更容易。 (P.S:'while(true)int main(){...'what?) – Borgleader

+1

請編輯你的問題以提供[mcve]。 –

回答

0

的問題是,您需要提示退出後調用cin.ignore()。當你使用cin來獲取'ch'變量時,換行符仍然存儲在輸入緩衝區中。調用cin.ignore(),忽略該字符。

如果你不知道,你會注意到程序在第二個循環打印一個換行符作爲名字。

您也可以使'ch'變量爲'cname'之類的字符串,並使用getline而不是cin。那麼你不必發出cin.ignore()調用。

#include <iostream>   // needed for Cin and Cout 
#include <string>    // needed for the String class 
#include <math.h>    // math functions 
#include <stdlib.h> 
using namespace std; 

#define baseCost 200.00 
#define drawerPrice 30.00 

int main() 
{ 
    while(true) 
    { 
     string cname; 
     char ch; 

     cout << "What is your name?\n"; 
     getline(cin, cname); 

     cout << cname; 

     cout << "\nWould you like to do another? (y/n)\n"; 
     cin >> ch; 

     // Slightly cleaner 
     if (ch != 'y' && ch != 'Y') 
      exit(1); 

     cin.ignore(); 

     /* 
     if (ch == 'y' || ch == 'Y') 
      continue; 
     else 
      exit(1); 
     */ 
    } 

    return 0; 
} 
+0

是的,謝謝 –

+0

當你有機會的時候,請點擊答案旁邊的複選標記,祝你學習愉快! – vincent

相關問題