I was trying to solve a programming challenge when I encountered this buffer issue. I am using getline command and I think cin buffer is not clearing but I don't know how to solve this. Can someone help me out?
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
usingnamespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string inStr;
unsignedlong val = 4294967295;
int inVal; //variable to store input integer value
unsignedlong result; //variable to store result
int count; // to count number of lines to print out
getline(cin,inStr);
istringstream buffer(inStr);
buffer>>count; //converting string to an integer value using stringstream
buffer.clear();
cin.clear();
while(count){
getline(cin, inStr);
istringstream buffer(inStr);
buffer >> inVal; //converting string to an integer value using stringstream
result = val - inVal;
cout << result << endl;
buffer.clear();
inStr.clear();
cin.clear();
count--;
inVal=0;
result=0;
}
return 0;
}
/The main function of member function .clear() is to turn off an error state bit that might have been set when reading data, it doesn't at any point clean the buffer content, i myself would empty the content of the string member if i needed clean the buffers.
Your problem isn't with the buffer not clearing. You're trying to store a value in a type that's too small to hold it, and it's overflowing.
In line 15, you define inVal as an int.
In line 26, you do buffer >> inVal - but consider the numbers in your input some of them are bigger than an int can hold and inVal will overflow, therefore giving you a wrong result.
Define inVal as an unsigned long as well.
unsignedlong inVal;
Some other suggestions:
review your overuse of clear()
line 14 should have type specifiers: unsignedlong val = 4294967295ul;
Don't use the same name for different things, as you've done with "buffer", shadowing the previous definition inside your while loop. This is legal, but not advised.