2012-12-22 72 views
2

可能重複:
Problem of using cin twice更新同一個變量多時間

此代碼的工作,但不是我的本意。每次我想按1在命令提示符下輸出會變成這個樣子,進入新的工資:

Comic books    : USD Input error! Salary must be in positive integer. 



的代碼應該在cout<<"\n\nComic books\t\t: USD ";停在第4行,但它只是與內部while循環執行。這是代碼:

double multiplePay =0; 

    cout<<"\n\nEnter employee pay for each job"; 
    while (1){ 
    cout<<"\n\nComic books\t\t: USD "; 
    //cin.get(); if enable, the first user input will be 0. this is not working. 

    std::string comic_string; 
    double comic_double; 
    while (std::getline(std::cin, comic_string)) 
    { 
     std::stringstream ss(comic_string); // check for integer value 

     if (ss >> comic_double) 
     { 
      if (ss.eof()) 
      { // Success so get out 
       break; 
      } 
     } 

     std::cout << "Input error! Salary must be in positive integer.\n" << std::endl; 
     cout<<"Employee salary\t: "; 
    } 

    comic = strtod(comic_string.c_str(), NULL); 

     multiplePay = comic + multiplePay; // update previous salary with new user input 
     cout << multiplePay; 
    cout << "Add other pay?"; // add new salary again? 
    int y; 

    cin >> y; 
    if (y == 1){ 


     cout << multiplePay; 
    } 
    else{ 
     break; 
    } 
    } // while 

cout << multiplePay; //the sum of all salary 

使用cin.get()就能解決問題,但第一個用戶輸入的薪水將成爲0,只有下一個輸入將被計算。請幫助我。提前致謝。

回答

3

您的問題是cin >> y;會讀一個int,但在輸入緩衝區離開結束行\n。下一次使用getline時,它會立即發現此行結束,而不是等待更多輸入。

+0

是的,這是問題所在。在最後的'if語句'中添加'cin.get()'解決了這個問題。再次感謝。 – sg552

1

std::basic_ios::eof()(在ss.eof())不起作用,因爲你可能認爲它的工作原理。

if (ss >> comic_double) 
    { 
     if (ss.eof()) 
     { // Success so get out 
      break; 
     } 
    } 

ss.eof()如果ss.get()電話或其他提取失敗,因爲你是在文件的結尾纔會是真實的。光標當前是否在最後並不重要。

請注意,您使用ss.get()解決這個問題很容易:

if (ss >> comic_double) 
    { 
     ss.get(); // if we are at the end ss.eof() will be true after this op 

     if (ss.eof()) 
     { // Success so get out 
      break; 
     } 
    }