C++ program does not allow me to give a second input - c++

I have two consecutive inputs, however, my program ends before allowing me to have my second input and just runs till the end, so:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double>v1;
for(double temp1; cin >> temp1;)
v1.push_back(temp1);
cout << "input1";
vector<double>v2;
for (double temp2; cin >> temp2;)
v2.push_back(temp2);
cout << "input2";
return 0;
}
I will be given the opportunity for input in the first for loop, however, after that, it doesn't let me give a second input and just goes on to print "input2".

It is ok to use the fail state of std::cin this way. You just need to reset std::cin before it can be used again.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double>v1;
for(double temp1; cin >> temp1;)
v1.push_back(temp1);
cin.clear(); //clear the error
cin.ignore(1000, '\n'); //ignore characters until we reach \n
cout << "input1";
vector<double>v2;
for (double temp2; cin >> temp2;)
v2.push_back(temp2);
cout << "input2";
return 0;
}
You could also #include <limits> and call
cin.ignore(numeric_limits<streamsize>::max(),'\n');
instead, to ignore unlimited characters until \n is reached.

Related

Error with input-validation using std::cin

I have implemented this check in my program to determine if the input is of the right type or not, and if not it asks to re-write the input.
If the input is wrong it works just fine but, if the input is right, you need to write it again. How can I avoid this? (you can find an example here https://godbolt.org/z/KjoTbc)
#include <iostream>
#include <limits>
int main() {
int input;
std::cin >> input ;
while (!(std::cin >> input)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Please, write an integer number\n";
};
}
You are not checking the first std::cin >> input ; and running while (!(std::cin >> input)), which asks input, unconditionally.
Remove the first unchecked reading and try this:
#include <iostream>
#include <limits>
int main() {
int input;
while (!(std::cin >> input)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Please, write an integer number\n";
}
}

How to make ignore function remove the delimiter as well

I wanted to grab a 10 character and store it in cstring and ignore the rest but I have having problem with it. The program doesn't halt for input the next time. How can I make it so that it halts and lets me enter again.
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char arr[11] = " "; //This is a cstring
string x; //will test with this variable
cout <<"Enter 10 character, rest will be ignored: \n";
cin.getline(arr, 10,'\n');
cin.ignore();
cout <<"Testing..\n";
cin >>x; //Should make the program halt
cout <<arr <<endl;
cout <<x;
}
cin.getline(arr, 10,'\n') will output at most 9 characters, not 10 characters, stopping if a line break is read before reaching 9 characters. If you want to receive 10 characters, you need to set the count parameter to 11 - the full size of arr - to include room for 10 characters + the null terminator.
Calling cin.ignore() afterwards without any parameters will ignore only 1 character. So, if the user types in more than count+1 characters, you are not ignoring them all. You should tell cin.ignore() to ignore all characters up to the next line break, if no line break was reached during the read.
Try this instead:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
char arr[11]; //This is a cstring
string x; //will test with this variable
cout << "Enter 10 character, rest will be ignored: \n";
if (cin.getline(arr, 11, '\n'))
{
// <= 10 characters w/ line break were read
}
else
{
if (cin.fail() && !cin.bad()) // exactly 10 characters w/o a line break were read, ignore the rest...
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
cout << "Testing..\n";
cin >> x; //Should make the program halt
cout << arr << endl;
cout << x;
}
That being said, this is C++, not C. It would be easier to use std::getline() instead, eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str; //This is a c++ string
string x; //will test with this variable
cout << "Enter 10 character, rest will be ignored: \n";
getline(cin, str);
if (str.size() > 10)
str.resize(10);
cout << "Testing..\n";
cin >> x; //Should make the program halt
cout << str << endl;
cout << x;
}

How to get string input n times? [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 3 years ago.
I have a C++ program. I want to get a number from the user (t) and force the user to enter line t times but the program's execution terminates after 1 iteration. This is the code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int t;
cin >> t;
for (int i=0; i< t; i++) {
getline(cin, str);
cout << str;
}
return 0;
}
Can anyone explain me why this happening and how to solve it?
Thank you my friends.
The newline character is still in the buffer when you do cin >> t so the next line you read will be blank. When you mix formatted input (>>) and unformatted (std::getline) you often get in situations like this and you need to take measures when switching to unformatted input. Example remedy:
#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main() {
string str;
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // skip the rest of the line
for(int i = 0; i < t; i++) {
if(getline(cin, str)) // check that the getline actually succeeded
cout << str << '\n';
else
break;
}
return 0;
}
When you enter your first character (the times to repeat), a character is left in the cin buffer - newlines are not consumed by cin >>. As a result, getline(cin, str) reads this character and takes it as the first input, which then empties the buffer out and lets you enter the others.
You can clear the buffer with std::cin.ignore(1); to remove that trailing character - this lets your code run as anticipated. Why not just use cin >> str, though? That solves the problem and avoids a call to getline.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int t;
cin >> t;
//clear one character out of buffer
cin.ignore(1);
//note that 1 is used for demonstration purposes
//in development code, INT_MAX, numeric_limits<streamsize>::max(),
//or some other large number would be best, followed
//by std::cin.clear()
for (int i=0; i< t; i++) {
cout << "input: ";
//you could use cin >> str; instead of getline(cin, str);
getline(cin, str);
cout << "got: " << str << std::endl;
}
return 0;
}
Demo

C++ - Taking variable number of integers from standard input, n number of times

I'm not able to figure out why the loop in following program is not running exactly testCount times. Please help to make it correct.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
size_t testCount;
cin >> testCount;
if(testCount < 0 || testCount > 100) return 0;
int input;
while(testCount--) {
string instr;
getline(cin,instr);
istringstream iss(instr);
while(iss >> input) {
cout << input << endl;
}
}
return 0;
}
Thanks. I got it. The problem is with getline(). First loop cycle is getting wasted as getline() is taking first line containing just new line character when I pressed enter key after typing testCount value.
std::ws is an input stream manipulator which ignores all whitespaces to the point where the first non-whitespace character is encountered.
Also, getline leaves whitespaces where they are if they don't fit in the line. cin >> ws will discard those.
Here's the bullet proof code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
size_t testCount;
cin >> testCount >> ws;
if(testCount < 0 || testCount > 100) return 0;
int input;
while(testCount--) {
cout << "testCount " << testCount << endl;
string instr;
cin >> ws;
getline(cin,instr);
istringstream iss(instr);
while(iss >> input) {
cout << input << endl;
}
}
return 0;
}

Fix spacing in copycat program

Here is my code for a basic copycat program that just copys whatever the user types:
#include <iostream>
using namespace std;
#include <string>
int main()
{
cout << "type something.. I dare you..." << endl;
for (;;)
{
string usrin;
cout << "You: ";
cin >> usrin;
cout << "Me: " << usrin;
}
return 0;
}
But when the user inputs more than one word i get this:
Me: more
You: than
You: Me: one
You: Me: word
You:
any and all help is appreciated! thank you!
You need to use cin.getline(usrin) instead of cin >> usrin.
cin >> usrin stops reading when it finds whitespace characters in the stream but leaves the rest of the stream for the next time cin is used.
cin.getline will read until the end of the line. However, you will need to change usrin to an array of char.
char usrln[MAX_LINE_LENGTH];
where MAX_LINE_LENGTH is a constant that is bigger than the length of the longest line you expect to see.
After each input, \n leaved behind in input buffer and read on next iteration. You need to flush your input buffer. Use
cin.ignore(MAX_INT, '\n'); //Ignores to the end of line
Add <limits.h> header.
#include <iostream>
#include <limits.h>
#include <string>
using namespace std;
int main()
{
cout << "type something.. I dare you..." << endl;
for (;;)
{
string usrin;
cout << "You: ";
cin >> usrin;
cout << "Me: " << usrin ;//<<endl;
cin.ignore(INT_MAX, '\n');
}
return 0;
}