Ending a loop when nothing is entered

前端 未结 1 658
有刺的猬
有刺的猬 2021-01-28 20:17

Usually I write a control loop as follows: Loop that enters writes ints into vector nVec until \"done\" is entered.

while (cin >> sString){
    if (sString         


        
相关标签:
1条回答
  • 2021-01-28 20:52

    You can't "not enter anything" into your token-wise extraction. The only way for your loop to stop is for the user to send end-of-file (Ctrl-D on Linux). I would personally say that this is the correct behaviour, but if you want to end on empty input, you need to read lines:

    Sales_item total;
    
    for (std::string line; std::getline(std::cin, line); )
    {
         if (line.empty()) { exit_program(); /* or "break" */ }
    
         std::istringstream iss(line);
         for (Sales_item book; iss >> book; )
         {
              total += book;
              std::cout << "The current total is " << total << std::endl;
         }
    }
    

    This way, you tokenize each line into possibly multiple books. If you just want one book per line, rip out the inner loop and just say std::istringstream(line) >> book;.

    0 讨论(0)
提交回复
热议问题