taking first string input and then ignoring the rest - c++

I want the user to enter a string, double and a long, but the thing is after the first time, the string is kind of being ignored and left empty and prompting for the double directly.
here's my code:
#include <iostream>
#include <string>
using namespace std;
int main () {
string name;
double price;
long serial;
cout << "Enter the dvd's name: "; getline(cin, name);
cout << "Enter the dvd's price (in $): "; cin >> price;
cout << "Enter the dvd's serial number: "; cin >> serial;
cout << endl;
cout << "Enter the dvd's name: "; getline(cin, name);
cout << "Enter the dvd's price (in $): "; cin >> price;
cout << "Enter the dvd's serial number: "; cin >> serial;
return 0;
}
as you can see the first time, i can enter a string the second time just sends me directly to the double, and even if i ignored the missing string, and put a double and then a long, it will print name as empty string.
What is wrong with my code?

I generally use istringstream in such cases (as shown below). But a better solution would be to use cin.ignore
#include <sstream>
int main () {
string name,line;
double price;
long serial;
cout << "Enter the dvd's name: "; getline(cin, line);
name = line;
cout << "Enter the dvd's price (in $): ";
getline(cin,line);
istringstream(line)>>price;
cout << "Enter the dvd's serial number: ";
getline(cin,line);
istringstream(line)>>serial;
cout << endl;
return 0;
}

The whitespace (carriage returns or space) after the serial number is not retrieved, and the getline then picks it up.
Edit: As johnathon points out, cin >> ws does not work right in this case (I'm sure I used this like this before, though I can't find an example).
Tested Solution: Instead, adding this after the serial number will get the carriage return (and any other whitespace) out of the stream so that it is ready for the next DVD name.
string dummy;
getline(cin, dummy);

Related

`cin >> variable` doesn't wait for input

#include <iostream>
#include <string>
#include "Friend.h"
#include "Address.h"
using namespace std;
int main() {
string name = "";
string street = "";
string city = "";
string state = "";
long phone_number = 0000000000;
int zip_code = 00000;
int feet = 0;
int inches = 0;
cout << "What is your friends name: ";
cin >> name;
cout << "What street does he live on: ";
cin >> street;
cout << "What city does he live in: ";
cin >> city;
cout << "What state does he live in: ";
cin >> state;
cout << "What is his 10 digit phone number: ";
cin >> phone_number;
cout << "What is his zip code: ";
cin >> zip_code;
cout << "How tall is he in feet: ";
cin >> feet;
cout << "And how many inches: ";
cin >> inches;
return 0;
}
This is my code. The problem here is: after I enter my phone number, it just doesn't wait for an input any more. It will output the cout << statements that follow automatically and then terminate it self. I am not sure why this happens.
Could someone help me please?
The variable phone_number is of type long, which is the same as long int. This means that you can only enter numbers as input for phone_number.
The best guess why it doesn't work for you is that you enter the phone number as: XXX-XXXXXXX (with the dash). The "-" splits the input, and the numbers after the dash are passed on to the next input variable zip_code.
If you try input for phone number as: 1234567890, then it works fine. If you want to use the dash, then consider changing phone_number to type string.
As an aside, take input for your string-type variables using getline() instead of cin << so that the compiler will continue reading all input until the ENTER key is hit.

Code skips the getline statement. I tried both getline and cin with no success

I read some answers regarding how to fix it but I'm trying to also understand the concept behind it (i.e. why does the first getline work fine).
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
string ticker = "";
string date = "";
int pprice;
int sprice;
cout << "Enter the stock ticker =>" << endl;
getline(cin, ticker);
cout << "Enter the purchase price =>" << endl;
cin >> pprice;
IT WORKS FINE UNTIL IT GETS TO HERE:
cout << "Enter the sell date =>" << endl;
getline(cin, date);
cout << "Enter the sell price =>" << endl;
cin >> sprice;
cout << ticker << endl;
return 0;
}
/*OUTPUT:
Enter the stock ticker =>
XYZ
Enter the purchase price =>
12.34
Enter the sell date =>
Enter the sell price =>
12.34
XYZ
*/
You're probably not using cin.ignore() in the correct place. It should be used after std::cin and before getline().
For Example:
int x;
string y;
cin >> x;
cin.ignore(INT_MAX);
getline(cin, y);
The idea is to remove the carriage returns, newlines etc that cin leaves behind on the stream which cause getline() to immediate take and return.

Extract a value from an input of type string and assign to a variable

I have a very basic question. It's about extracting a value from a string input and then assigning this value to an int and then copying out this integer to screen.
Here is my code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string mystr;
float price;
int quantity;
cout << "What is your name? ";
getline (cin,mystr);
cout << "Hello Mr. " << mystr << endl;
cout << "Enter price: ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << "Enter quantity: ";
getline (cin,mystr);
stringstream (mystr) >> quantity;
cout << "Total price: " << quantity*price << endl;
cout << "Thank you for purchasing our product!";
return 0;
}
So the question is: when asked to enter price. Can I type "Price is 16" for example and the program is supposed to extract the 16 from the input and assign it to price?
If you allow that type of input, you would have to strip off the Price is portion before you can then read the 16 portion. Easiest way to do that is to simply put the input into a stringstream and call its >> operator in a loop until you reach a number or the end of the stream, eg:
cout << "Enter price: ";
getline(cin, mystr);
stringstream ss(mystr);
do
{
if (ss >> price)
break;
}
while (!ss.eof());
if (!ss)
{
// no price provided, do something...
}

String getline(cin,variable) function is skipping some lines of code

My program skips some code when I use the getline(cin,variablehere) function. I don't know whats wrong with the code. See the output below
#include <iostream>
#include <string>
using namespace std;
int main()
{
string getfirstname;
string lastname;
string address;
int contactnumber;
cout << "Enter First name : ";
getline(cin, getfirstname);
cin.ignore();
cout << "Enter Last name : ";
getline(cin, lastname);
cin.ignore();
cout << "Enter Address : ";
getline(cin, address);
cin.ignore();
cout << "Enter Contact number : ";
cin >> contactnumber;
cin.ignore();
CurrentNumberOfContacts += 1;
cout << "Successfully added to contact list!" << endl << endl;
cout << "Would you like to add another contact ? [Y/N] ";
cin >> response;
//more lines of codes below
return 0;
}
I have inputed 'int' as data type because it will contain numbers only
I recommend removing all the cin.ignore() commands.
One of the problems with user input is that the >> operator does not take the RETURN character out of the stream so if you follow it with a getline() the getline() will read the RETURN character instead of what you want to type in.
So I would change all your getline() to this:
// cin >> ws will skip any RETURN characters
// that may be left in the stream
getline(cin >> ws, lastname);
Also remove all of your cin.ignore() commands. They are not doing anything useful when used after a getline() command and if you change your getline() commands as I showed they should not be necessary at all.
So this should work:
int main()
{
string getfirstname;
string lastname;
string address;
char response;
int contactnumber;
int CurrentNumberOfContacts = 0;
cout << "Enter First name : ";
getline(cin >> ws, getfirstname);
cout << "Enter Last name : ";
getline(cin >> ws, lastname);
cout << "Enter Address : ";
getline(cin >> ws, address);
cout << "Enter Contact number : ";
cin >> contactnumber;
CurrentNumberOfContacts += 1;
cout << "Successfully added to contact list!" << endl << endl;
cout << "Would you like to add another contact ? [Y/N] ";
cin >> response;
//more lines of codes below
return 0;
}
Strictly speaking not all of your getline() functions need to employ the cin >> ws trick. I suppose the (incomplete) rules are as follows:
If you use a std::getline() after a >> then use:
std::getline(cin >> ws, line);
Otherwise just use:
std::getline(cin, line);
cin >> and getline do not cooperate very well. They have different strategies for how to deal with whitespace. getline removes the newline character, but cin >> leaves it. This means that after you use cin >> to read something, there will be a newline character left waiting in the input stream for the next getline to "use". Which means it will read an empty line into the string.
2 things. First, you don't really need cin.ignore() in this case as your using
getline().
before
cin >> variable
Second, I don't know why your program doesn't run, but I would suggest using a
getline()
call and see if that works. But I see no reason why your code is not working.
The answer provided by #Galic is quite good but If you want to read a line of characters without discarding the leading spaces you need another solution.
You could do:
char a='\n';
while (a=='\n')
{
cin.get(a);
}
cin.unget();
before doing your first getline. This assumes no trailing space resulting from a previous cin and that your first input line is not empty.

How to skip a field without entering value in c++

In the below code phone number is not mandatory. How can i skip the field? If i press enter it is still waiting for my input. I want to skip the phone number field if necessary. Is that possible in C++.
#include <iostream>
using namespace std;
int main()
{
string id, name, phone, dob;
cout << "Enter id";
cin >> id;
cout << "Enter name";
cin >> name;
cout << "Enter phone number";
cin >> phone;
cout << "Enter date of birth";
cin >> dob;
}
std::string phone_number;
std::getline(std::cin, phone_number);
gets what ever was entered on that line including nothing.
Use getline(cin, name); instead of cin>>name;. It will put a complete line to the variable. If you just press ENTER it will put an empty line.