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

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().

Related

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

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);

input char* without using string library [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 4 years ago.
I'd like to do the following, but without including string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1,s2;
char c;
cout<<"input a string: "<<endl;
cin>>s1;
cout<<"input a character: "<<endl;
cin>>c;
cout<<"input another string: "<<endl;
cin>>s2;
}
When I try this:
#include <iostream>
using namespace std;
int main()
{
char s1[128], s2[128];
char c;
cout << "input a string: " << endl;
cin.getline(s1, 128);
cout << "input a character: " << endl;
cin >> c;
cout << "input another string: " << endl;
cin.getline(s2, 128);
}
I run into issues... basically when I enter the character it also enters for the second string, and I never get a chance to enter it. please help thanks.
Rik
Use cin.get() after use "cin >> var". This method extract symbol new line from buffe

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 won't getline function work multiple times in a for loop with an array of structures? [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 7 years ago.
I have a little problem. I've created a program that asks user to enter part's name and part's price for four diffrent parts. Each name and price fills a structure, and I have an array of four structures. When i do a for loop to fill all the names and prices, my getline functon doesn't work properly, it simply just skipps the entering part after I enter the first part's name. Can you please tell me why?
Here's my code:
#include <iostream>
#include <string>
struct part {
std::string name;
double cost;
};
int main() {
const int size = 4;
part apart[size];
for (int i = 0; i < size; i++) {
std::cout << "Enter the name of part № " << i + 1 << ": ";
getline(std::cin,apart[i].name);
std::cout << "Enter the price of '" << apart[i].name << "': ";
std::cin >> apart[i].cost;
}
}
std::getline consumes the newline character \n, whereas std::cin will consume the number you enter and stop.
To illustrate why this is a problem, consider the following input for the first two 'parts':
item 1\n
53.25\n
item 2\n
64.23\n
First, you call std::getline, which consumes the text: item 1\n. Then you call std::cin >> ..., which recognises the 53.25, parses it, consumes it, and stops. You then have:
\n
item 2\n
64.23\n
You then call std::getline for a second time. All it sees is a \n, which is recognised as the end of a line. Therefore, it sees a blank string, stores nothing in your std::string, consumes the \n, and stops.
To solve this, you need to make sure the newline is consumed when you store the floating-point value using std::cin >>.
Try this:
#include <iostream>
#include <string>
// required for std::numeric_limits
#include <limits>
struct part {
std::string name;
double cost;
};
int main() {
const int size = 4;
part apart[size];
for (int i = 0; i < size; i++) {
std::cout << "Enter the name of part № " << i + 1 << ": ";
getline(std::cin,apart[i].name);
std::cout << "Enter the price of '" << apart[i].name << "': ";
std::cin >> apart[i].cost;
// flushes all newline characters
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}

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.