This question already has answers here:
Using fflush(stdin)
(7 answers)
Closed 3 years ago.
I wrote this simple addition software, in which I wanted the addition to end when the user entered 'n'. My current code works just fine. But I made two more variations of the same code, one worked, and one gave me an error. Can anyone tell me what is happening exactly in each case?
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
cin>>a;
b+=a;
}while(getchar()!='n');
cout<<b;
//works just fine
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
fflush(stdin);
cin>>a;
b+=a;
}while(getchar()!='n');
cout<<b;
//this one works too
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
a=getchar();
b+=a;
}while(a!='n');
cout<<b;
//doesn't work
I wanna know why fflush(stdin) have no effect on the code. If I just keep writing my input like "20, 30, 50, n" instead of "20, y, 30, y, 50, n" I get the same result in both working codes. Why does this happen?
First of all, it is best to use C++ standard input and output std::cin and std::cout respectively.
The main problem with your code is that it conflicts with types you want:
You want to add integers int together and to see if the input is the character char 'n'.
What's happening is the legacy C fflush(stdin) "flushes" or clears the standard input stream buffer (read more here: https://www.google.com/amp/s/www.geeksforgeeks.org/use-fflushstdin-c/amp/) and getchar() receives character input from the user. getchar() returns a character and by deduction, your code transmutes that input into its integral int ASCII-ANSI numerical integral equivalent.
This means that on the third version, when you input "30", what actually is collected is '3' and without flushing the buffer, the next input is considered '0' causing a problem.
I suggest you use a control structure to check if the user wants to continue before receiving input to add:
int a = 0, b =0;
char c = 0; // for y/n responses
std::cout << "Welcome to my ... "; //just finish this string
do{
std::cout << "input integer: "; // for better formatting leave at least one space after the colon
std::cin >> a;
b += a;
std::cout << "Continue? n to stop: "
std::cin >> c;
} while (c != 'n')
std::cout << "Added: " << b;
Related
This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 2 years ago.
Im a new user of c++ and I am stuck with a problem.
If the input for the int variable 'x' is anything other than a number, then c++ seems to skip the cin associated with the char variable 'y'. I tried to use cin.ignore and cin.clear, but they dont seem to work. Any ideas on how to make the program still ask the value for char 'y' when the value for int 'x' is anything but a number(eg. 'a' '*' '') ?
#include <iostream>
using namespace std;
int main()
{
int x;
char y;
cout << "num: ";
cin >> x;//int input
cout << endl;//blank line
cout << "char: ";
cin >> y;//char input
cout << endl;//blank line
return 0;
}
Are you passing parameters to ignore?
The first parameter is the maximum of chars to be ignored and the second one is the flag that it should stop ignoring after findind it (which in the example below I've put '\n')
cin.clear();
cin.ignore(1000, '\n');
To summarize, the code says: Clear up to 1000 chars or up to the first '\n'.
I'm very new to C++. I started teaching myself C++ last week, and up until now, I haven't had any real problems.
I use Microsoft Visual Studio 2017, and I'm having problems with if and else statements. You see, I'm making this very limited calculator. Basically, the program gives you the 4 basic mathematical operations, and you choose which operation you want to use to calculate by entering either 1, 2, 3, or 4. Then, it runs another program which you can then calculate. (e.g.: 2 is for subtraction, if you enter 2, it will run the subtraction calculator)
Here's the code for the program.
#include "stdafx.h"
#include "iostream"
using namespace std;
int main(){
int add = 1;
int sub = 2;
int mul = 3;
int div = 4;
cout << "Extremely Limited C++ Calculator: Enter a number between one and
four to start calculating and press enter."
<< '\n'
<< "LEGEND"
<< '\n' << "1 = Addition"
<< '\n' << "2 = Subtraction"
<< "\n" << "3 = Multiplication"
<< '\n' << "4 = Division"
<< '\n' << "Operation: ";
if (cin >> add) {
system("start C:\\CalculatorApps\\addition.exe");
return 0;
}
if (cin >> sub) {
system("start C:\\CalculatorApps\\subtraction.exe");
return 0;
}
if (cin >> mul) {
system("start C:\\CalculatorApps\\multiplication.exe");
return 0;
}
if (cin >> div) {
system("start C:\\CalculatorApps\\division.exe");
return 0;
}
}
So I have the addition.exe and subtraction.exe done, but the problem is that no matter what number I enter, it will always run addition.exe. In the subtraction calculator, I experimented having the user choose if they wanted to subtract more than 2 numbers, but that also didn't end up working because it was ignoring if statements. I also at one point had an else statement on both the subtraction calculator and the main program that takes you to the calculators that displayed text reading that the number they entered was not a valid choice and to enter a valid choice, but even that was ignored by the program. Now, maybe I didn't look hard enough on the internet, but I couldn't find one that helped me out. If you know the answer, please tell me but in words that I can understand (I am new after all), or please link me to another question that has been answered that will solve my question.
Thank you in advanced!
cin is an object of class istream that represents the standard input stream. It corresponds to the cstdio stream stdin. The operator >>overload for streams return a reference to the same stream. The stream itself can be evaluated in a boolean condition to true or false through a conversion operator.
cin provides formatted stream extraction. The operation cin >> x;
where "x" is an int will fail if a non-numeric value is entered. So:
if(cin>>x)
will return false if you enter a letter rather than a digit.
As you are always entering a digit, your first statement if(cin>>sum) is always true. So, your other statements are skipped.
I need to read an unknown length sequence of integers and then i need to find the longest monotonic subsequence in it. The sequence ends with EOF sign and its elements are to separated with spaces.
I'm not really bothering the algorytm of finding the subsequence now I'd like to make sure that I'm reading elements of the sequence in a right way. Below is a code which is supposed to do the job but there's a bug which I don't get right now.
#include <iostream>
using namespace std;
int main()
{
int sum=0;
int a=0;
cout << "Give me a number: ";
// while (!fin.eof()) {
while (cin >> a) {
cin >> a;
sum +=a;
cout << "Sum is: " <<sum << endl;
/* Thats the place where whole magic is supposed to happen.
I'm really confused however, because after entering i.e. 2 3 4 2 4
and pressing <Enter> five times shows an answer "The sum is <proper sum>"
and the answer "The final sum is: ... " doesn't show at all.
*/
}
cout << "final sum is : " << sum;
cout << "Hello world!" << endl;
return 0;
}
I'll be very grateful if anyone could answer my questions and explain if and where I'm wrong.
I'll appreciate any help!
Well, for one, you seem to be checking on the state of fin, but you never open that file and you never read from it. I'm guessing you meant to use std::cin everywhere, or fin everywhere; I'll stick to std::cin, but fin would work the same way.
The problem is that you first check for end-of-file and then read and use the data. This means that if the read failed, you aren't told about this. Instead of
while (std::cin) {
std::cin >> a;
sum += a;
}
use
while (std::cin >> a) {
sum += a;
}
This will still perform the check, but after the read, meaning that if the read failed, you don't go into the body of the loop, and don't use the (nonsense) data.
The fin case looks much the same:
std::ifstream fin("mydata.txt");
while (fin >> a) {
sum += a;
}
Note that there's no need to explicitly check for whether you reached the end of the file; checking the state of the stream will catch that error, as well as any errors due to being unable to parse a number. If instead we did
while (fin >> a, !fin.eof())
this would correctly handle the case where you read the whole file, but loop infinitely if it contained something other than a number.
First, decide whether you're reading from the file (fin) or the program's input (std::cin). Currently, you're reading from one and checking the other for eof.
If you're reading from the file, then you'll need to open it. Otherwise, remove fin to avoid confusion.
Then you should check for eof (and other error conditions) after attempting to read, and before using the result:
while (std::cin >> a) { // or `fin`, if that's where you're reading from
// your code using 'a' here
}
Title probably sounds confusing so first I'll show you my code, I made this simple program to get two input values and multiply them, and another thing, but that's not important, It works correctly:
#include <iostream>
using namespace std;
main()
{
int a,b,c,d,e;
char j = 4;
cout << "Welcome to Momentum Calculator\n\n";
cout << "------------------------------\n";
cout << "Please Enter Mass in KG (if the mass in in grams, put \"9999\" and hit enter): \n\n";
cin >> a;
if (a==9999) {
cout << "\nPlease Enter Mass in grams: \n\n";
cin >> d;
}
else {
d = 0;
}
cout << "\nPlease Enter Velocity \n\n";
cin >> e;
if (d == 0)
{
c = (a*e);
}
else {
c = (e*d)/100;
}
cout << "\nMomentum = " << c;
cin.get();
cin.ignore();
while (j == 4)
{
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
main();
}
}
Now as you can see, my variable is an int (integer) and my problem is If I enter an English letter (a-z) or anything that is not a number will cause it to repeat my program unlimited times at an unlimited speed. I want a string/char to see if my var "a" is a letter or anything but don't know how to. I can do it, however, I want user to input only one time in "a" and mine makes him to enter again. Please Help :)
There is a function called isalpha in ctype library, checks whether your variable is an alphabetic letter so you can do using isalpha function.
Will isdigit or isalpha from standard library help you?
P.S.
1KG contains 1000 grams, so you should divide by 1000, not by 100;
UPDATE:
Seems I understood your question...
You need cin.clear(); before cin.get() and cin.ignore().
Otherwise the these calls won't do anything, as cin is in an error state.
I think you can get a as an String, and see if it contains English letter or not, if it contains, again ask for the input ( you can do it in a while loop ). And when a correct input entered, parse it and find what is it's number.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Program not waiting for cin
I wrote the following code:
#include <iostream>
using namespace std;
void search(int pre, int a, int b, int x) {
char c;
cout << "Is the number " << ((x == 2) ? b : a) << endl;
c = cin.get(); ////// this does not block
if (c == 'y') return;
else {
cout << "Is the number " << ((x == 2) ? b : a) << " closer to your number than " << pre;
c = cin.get();
if (c == 'y') {
search(a, a, (a + b) / 2, 2);
} //c=='y'
else search(a, (a + b) / 2, b, 1);
}
}
int main() {
int N;
cout << "Enter N? ";
cin >> N;
search(N, 1, N, 1);
return 0;
}
No need to worry if you don't understand the logic because my question is not regarding that.
In the search function, there are two cin.get(), where i need the user to enter a character. My problem is that the the program blocks for input only after the second cin.get().
For example:
Is the number 7 //program doesn't wait after this
Is the number 7 closer to your number than 8 //program blocks here for an input
Why does it do so?
There are at least two problems in your code. The first is that you're
leaving characters in the buffer after inputting N. The simplest
solution is to just add a call to std::cin.ignore( INT_MAX, '\n' );
after std::cin >> N;; a better solution (because it allows for more
error checking) would be to use std::getline to read the complete
line, then parse it using std::istringstream.
The second problem is that you're assigning the results of
std::cin.get() into a char. std::cin.get() returns an int,
which may be EOF. And you really want to check whether it is EOF
before converting the int to char: you cannot check after because
either some legal char will compare equal to EOF (plain char is
signed), or the char will never compare equal to EOF (plain char
is unsigned). The other alternative is to do something like:
if ( !std::cin.get( c ) ) {
// EOF or error seen...
}
each time you want to read a char. (This might be better in your
case, since if you do read EOF, all further calls to std::cin.get()
will return EOF.)