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...
std::cin >> nextVal(whilecondition) to allow the program to wait for your slow human fingers. That is exactly what is happening to you here, the program is waiting, unable to determine if it should go into another loop. It will keep waiting until the next input or until you give it a clue that you have finished typing(e.g. by pressing Enter). If you were to debug your program and put a break point inside thewhileloop and another right after it, you would see clearly when thing get executed.std::endldoes. Use'\n'to end a line unless there's a good reason. not to.