Problem with condition no While in C++
Hello, I am studying from Bjarne's book "PROGRAMMING Principles and practice Using C++". I'm trying to do drill number 1 of Chapter Four. The exercise says to make a program that consists of a while-loop that reads and prints two integers and stops when it is written|, however, when I write | (or anything other than a number) the program stays in an infinite loop. If anyone can explain to me what is wrong with my code, I have already tried to read in book about conversions from int to char and vice versa and even then the error persists, take a look.
#include <...\Projects\std_lib_facilities.h>
int main()
{
//drill's
//1 - inicio
/*escrever um programa que consiste em um while-loop que leia dois int e termine quando
é escrito | */
int n=0, n1=0;
cout << "Write a int. To stop the program hit |";
while (n != '|' || n1 != '|' )
{
cin >> n >> n1;
system("cls");
cout << n << " " << n1 << "\n";
}
}
1 answers
As per the SO post (in English):
Https://stackoverflow.com/questions/10349857/how-to-handle-wrong-data-type-input
The reason the program goes into infinite looping is because of a flag (flag) of invalid device input std:: cin .
What needs to be done is to clear the flag and discard the invalid entry from the input buffer.
After correction, the code is like this:
while (n != '|' || n1 != '|')
{
// limpa a flag
std::cin.clear();
// Descarta a entrada
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin >> n >> n1;
system("cls");
std::cout << n << " " << n1 << "\n";
}
The "wrong" input is occurring because of reading a (type) character "| " in a variable of type numeric n
or n1
.
For more details:
Other possibilities to correct:
- read content | for a variable type
char
- read each value to a buffer of type
string
and then convert to integer with the function std:: stoi
Update:
After applying the second correction suggestion, the looping looks like this:
int n = 0, n1 = 0;
std::string buffer;
std::cout << "Write a int. To stop the program hit |";
while (n != '|' || n1 != '|')
{
// Lê a primeira entrada
std::cin >> buffer;
// Se for um "|", sai do looping
if (buffer == "|")
break;
// Converte para inteiro
n = std::stoi(buffer);
// Lê a segunda entrada
std::cin >> buffer;
// Se for um "|", sai do looping
if (buffer == "|")
break;
// Converte para inteiro
n1 = std::stoi(buffer);
// Limpa a fila std::cin
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// std::cin >> n >> n1;
//system("cls");
std::cout << n << " " << n1 << "\n";
}
Even with this fix, the above code is still subject to other errors.
Below is a reading suggestion to better understand how the data input and output system works in C++: