Getline command gets skipped when an integer cin statement is above [duplicate] - c++

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
So I made this to try understanding classes and this error keeps coming up where in the command prompt tab, it doesn't ask the user to input the next required input when an integer is being asked. I added a comment in the code below for you to know where the error arises from.
#include <iostream>
using namespace std;
class Anime
{
public:
string Name;
int Year;
string Genre;
Anime(string aName, int aYear, string aGenre)
{
Name = aName;
Year = aYear;
Genre = aGenre;
}
};
int main()
{
string aniName;
int aniYear;
string aniGenre;
// This asks for the year
cout << "Anime Year: ";
cin >> aniYear;
// The "Anime Name" line runs but the input for aniName is not asked and skips to the next input
cout << "Anime Name: ";
getline(cin, aniName);
cout << "Anime Genre: ";
getline(cin, aniGenre);
Anime Anime1(aniName, aniYear, aniGenre);
cout << Anime1.Name << endl;
cout << Anime1.Year << endl;
cout << Anime1.Genre << endl;
}
When i make the integer the last input, it works perfectly, but at if I don't want it to be the last one. In that case, what do I do? Any answer is greatly appreciated.

Try to add #include <string>
And add below code upper the input code.
cin >> aniYear;
// The "Anime Name" line runs but the input for aniName is not asked and
skips to the next input
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Anime Name: ";
getline(cin, aniName);

Related

Creating a struct during while loop skips over input [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 1 year ago.
I'm trying to create a struct and collect its inputs from the user with a while loop, however on the second iteration it just seems to skip past the inputs.
#include <iostream>
#include <list>
struct Student {
std::string name;
std::string course;
float mark;
};
int main() {
std::list<Student> students;
while (students.size() < 2) {
Student student;
std::cout << "Student Name:" << std::endl;
std::getline (std::cin, student.name);
std::cout << "Course and Mark:" << std::endl;
std::cin >> student.course >> student.mark;
students.push_back(student);
}
for(auto const& student: students) {
std::cout << student.name << std::endl;
}
return 0;
}
The output looks like so:
Student Name:
Ari Stackoverflow
Course and Mark:
course543 56.2
Student Name: <---- skipped :(
Course and Mark:
Steve Jobs
As you can see, one the second iteration it skips over getting the name, not sure why.
The problem here is that when you press "Enter" after your second line of input, that newline is fed to std::getline(std::cin, student.name); on the next iteration. And so students[1].name would be an empty string.
To get around this, add std::cin.ignore() or std::cin.get() after reading your second line. This tells cin to ignore the newline.

when saving to file, words after white space are ignored [duplicate]

This question already has answers here:
How to read a complete line from the user using cin?
(4 answers)
Closed 6 years ago.
I've been working on saving to files and this was the result. The only problem is that anything after a space is ignored, (if you typed "john smith") it would print
("the last person to use this file was: john") I am using codeblocks with the GNU GCC compiler. Here is the code:
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
string name;
ofstream saveData;
ifstream Data;
Data.open("Info.data", ios::binary);
Data >> name;
Data.close();
cout << "The last person to use the file was " << name << endl;
cout << "What is your name?" << endl;
cin >> name;
saveData.open("Info.data", ios::binary);
saveData << name;
cout << name << endl;
system("PAUSE");
saveData.close();
return 0;
}
thanks
For strings objects of ifstream (including cin) use input from beginning till the first space, and space is SPACE, TAB, and NELINE.
So, you should use getline instead cin >>
Try this:
Data.open("Info.data");
getline(Data, name);
Data.close();
and
cout << "What is your name?" << endl;
//cin >> name;
getline(cin, name);
UPDATE:
By the way, in your code
after
Data.open("Info.data", ios::binary);
you use
Data >> name;
So, stream opened in binary mode is read by >> - it is not so good.

Why does this small change halt my C++ program?

I'm new to C++ trying to wrap my head around the fundamentals. This small alteration gives a subtle change in my program behaviour, preventing it's complete run. The problem is every time I arrive at the prompt to enter school, I can't input any text.
Software Info:
OS: Ubuntu 14.04 LTS
G++ version: 4.8.4
This is the code which runs fine:
#include <iostream>
using namespace std;
int main (int argc, char* argv[])
{
string fName, DOB, school;
int age;
cout << endl;
cout << "What is your name: ";
getline (cin, fName);
cout << "What school do you attend: ";
getline (cin, school);
cout << "How old are you: ";
cin >> age;
cout << school << endl;
return 0;
}
This is the code which halts:
#include <iostream>
using namespace std;
int main (int argc, char* argv[])
{
string fName, DOB, school;
int age;
cout << endl;
cout << "What is your name: ";
getline (cin, fName);
cout << "How old are you: ";
cin >> age;
cout << "What school do you attend: "; // this is the only change.
getline (cin, school);
cout << school << endl;
return 0;
}
The only change is moving:
cout << "What school do you attend: ";
getline (cin, school);
from lines 13 & 14 to lines 15 & 16.
Can anyone tell me why this is happening?
Like others have said, there could be a character remaining in the input buffer, most likely the \n charachter when you pressed Enter.
You could add:
while((c = getchar()) != '\n' && c != EOF);
Right after your cin to get all the remaining characters in the buffer, but this is mostly for C.
In C++ you could instead:
std::cin.ignore(256,'\n');
Which will get and discard the next 256 characters it finds in the buffer or until it finds a char equal to the one passed as the second argument, in this case a \n or newline character. Note that for the second parameter, when it is found it is also discarded.
The 'Enter' after age is consumed as a character for school variable in the second program. The easiest solution is to read a dummy character( a useless variable) after reading 'age' in the second program.

Why is std::getline() skipped? [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
c++ getline() isn't waiting for input from console when called multiple times
(9 answers)
Closed 8 years ago.
I have this C++ simple program;
#include <iostream>
using std::endl;
using std::cout;
using std::cin;
using std::getline;
#include <string>
using std::string;
struct Repository
{
string name;
string path;
string type;
string command;
};
int main()
{
Repository rp;
cout << "\nEnter repo name: ";
cin >> rp.name;
cout << "Enter repo path: ";
cin >> rp.path;
cout << "Enter repo type: ";
cin >> rp.type;
cout << "Enter repo command: ";
getline(cin, rp.command);
cout << "\nRepository information: " << endl;
cout << rp.name << "\n" << rp.path << "\n" << rp.type << "\n" << rp.command << endl;
return 0;
}
When execution reaches getline(cin, rp.command) the program just print "Enter repo command: " and skips the getline(cin, rp.command) line so that the user is not given time to respond. What could be the possible problem?
Duplicate question answered here.
basically, cin>> doesn't remove new lines from the buffer when the user presses enter. getline() mistakes this for user input along with enter.
You can use cin.ignore() to get rid of those extra characters before using getline().
There are newline characters in cin's buffer, so getline() takes it as an input from user.
You should flush cin buffer before using getline().

Check if string is not a number before converting it to a int [duplicate]

This question already has answers here:
How to check std::string if its indeed an integer?
(3 answers)
How to say != 0-9 in c ++ [duplicate]
(6 answers)
Closed 9 years ago.
I have got a terminal app that gets user input stores it in a string then converts it into a int. The problem is if the user inputs anything that is not a number the conversion fails and the script continues without any indication that the string has not converted. Is there a way to check of the string contains any non digit characters.
Here is the code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string mystr;
float price=0;
int quantity=0;
cout << "Enter price: ";
getline (cin,mystr); //gets user input
stringstream(mystr) >> price; //converts string: mystr to float: price
cout << "Enter quantity: ";
getline (cin,mystr); //gets user input
stringstream(mystr) >> quantity; //converts string: mystr to int: quantity
cout << "Total price: " << price*quantity << endl;
return 0;
}
Just before the conversion here: stringstream(mystr) >> price; I want it to print a line to the console if the string is Not a Number.
You can find out if a read of an int has been successful or not by checking the fail() bit of your input stream:
getline (cin,mystr); //gets user input
stringstream priceStream(mystr);
priceStream >> price;
if (priceStream.fail()) {
cerr << "The price you have entered is not a valid number." << endl;
}
Demo on ideone.
If your want to check if the price user inputs is a float, you can use boost::lexical_cast<double>(mystr);, if it throws an exception then your string is not a float.
It's going to add a bit to your code, but you can parse mystr with isdigit from cctype. The library's functions are here. isdigit(mystr[index]) will return a false if that character in the string isn't a number.