While the loop breaks and I don't know why
I was writing code for the counter. If I give "a" as input, it should +1 counter and show it on screen. But when I do that, it shows 1 on the screen and the program ends. I want it to work until I give some other character as input. What mistake am I making?
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
else
break;
system("cls");
cout << Counter;
}
return 0;
}
source to share
Try the following:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
// else
// break;
system("cls");
cout << Counter;
}
//system("pause");
return 0;
}
Yours else break;
is the reason why you close after any intervention. Basically, after any iteration, it breaks because of any input a
. However, by running the code above, you will see the counter incrementing on every input you enter a
, and it won't break.
This will give you the main operation you are looking for, which increments the counter based on the input of a, otherwise does nothing.
Change: . The above code will buffer your input and read everything, so if you have 5 a
like below aaaaa
it will read it and output 5 for the counter.
If you want to exit the loop, I suggest the following:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
cin >> t;
// t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
else
break;
system("cls");
cout << Counter;
}
//system("pause");
return 0;
}
I tested it and it works. It seems that using cin.get()
is reading buffered input from the console (I think). Not too sure about specifics, but cin >> t
does the trick.
Edit 2: Did some readings and I think it cin.get()
will use the next character after typing, but in this case it is a text space \n
, so it will always be broken in your original code.
source to share
The problem is that when you type yours 'a'
, you are probably also hitting Enterwhich is interpreted as different char
. This second one is char
definitely not a
, so your program breaks. This can be verified by simply outputting what you are reading:
for (;;) {
std::cout << '?';
char t = std::cin.get();
std::cout << (int)t << '\n';
if (t != 'a') break;
}
std::cout << "done\n";
What prints at startup:
?a
97 // this is 'a'
?10 // this is '\n', note the additional ?
done
The simplest solution would be to use the input stream operator on cin
, which would strip whitespace in the input (when it get()
doesn't):
char t;
for (;;) {
std::cout << '?';
std::cin >> t;
std::cout << (int)t << '\n';
if (t != 'a') break;
}
std::cout << "done\n";
What produces at startup:
?a
97
?b
98
done
as you expected.
source to share