Search code examples
c++visual-studio-2022end-of-line

Problem with end of line in Microsoft Visual Studio 2022 - C++ primer example


I've been learning C++ in the last couple of days (I've only done some classes in CS some years ago). I'm currently reading and learning with "C++ Primer" 5th edition, and I've encountered this issue which I'm not sure it is related to the code itself or Microsoft Visual Studio 2022...

In the book, we are given this example: enter image description here

I understand all the principles behind this code, as of my knowledge at this point, and I managed to write a similar one using Microsoft Visual Studio 2022:

#include <iostream> 

int main() 
{
int currVal = 0, nextVal = 0;
std::cout << "Write a series of numbers: " << std::endl;
int i = 1;

   if (std::cin >> currVal) 
   {        
       while (std::cin >> nextVal)
       {
          if (nextVal == currVal) 
              ++i; 
          else 
          { 
              std::cout << currVal << " occurs " << i << " times" << std::endl;
              currVal = nextVal;
              i = 1;
          }
        }
    std::cout << currVal << " occurs " << i << " times" << std::endl;
   }
return 0;
}

However, when I run the program and introduce the sequence given in the book - 42 42 42 42 42 55 55 62 100 100 100 - my program stops and does not procede to count the number 100, as per this image: enter image description here

Only when I press another key/non integer will my program finish: enter image description here

Is this a problem with my code or the compiler?

Thank you in advance for the help! :D

I've also tried to copy and paste the code from the book and the compiler does the same thing. I imagined it must be something about the program that does not recognizes the end of the line... I've tried some solutions given by ChatGPT, like adding !std::cin.eof() to the while loop or clearing the input buffer with std::cin.clear(); td::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); at the end of the code and it still didn't work...


Solution

  • Is this a problem with my code or the compiler?

    Neither. The input is line buffered so you need to press enter for the program to start processing what you've entered. Once it's done processing the numbers you entered, it'll stand and wait for new input at

    while (std::cin >> nextVal)
    

    In its current form, in order for the program to terminate, you can close the input stream by pressing CTRL-Z + Enter (Windows) / Enter + CTRL-D (*nix). That will cause the extraction in std::cin >> nextVal to fail and put std::cin in a failed state. std::cin is convertible to bool via its member function operator bool() const and it will return false if std::cin is in a failed state and true if it has no errors.