2012-12-22 70 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; 
     } 
    }