The user is prompted to "enter a middle initial". What happens if they enter a space, full name, or maybe a letter followed by a period '.' ?
How can we modify the program to handle this using cin.ignore?
This is the code I currently have:
I commented out the area I'm having trouble with.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string fname, lname;
char MI;
cout << "Please enter your first name: ";
cin >> fname;
cout << "Please enter your middle initial: ";
cin.ignore(1, '\n');
cin.get(MI);
cout << "Please enter your last name: ";
//cin.ignore('\n')
cin >> lname;
cout << "Your name is " << fname << " " << MI << " " << lname << endl;
return 0;
}
When I have this other cin.ignore in it still doesn't do anything and the last name reads the extra inputs. I've tried adding a number of characters to read and it still doesn't fix the problem. When I run it it just skips the input for last name. I also tried changing the last name input to getline but if still didn't do anything.
You can just use std::getline and std::istringstream:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string fname, lname;
std::string MI;
std::cout << "Please enter your first name: ";
std::getline(std::cin, fname);
std::istringstream iss(fname);
iss >> fname;
do
{
std::cout << "Please enter your middle initial: ";
std::getline(std::cin, MI);
} while (MI.size() != 1);
std::cout << "Please enter your last name: ";
std::cin >> lname;
std::cout << "Your name is " << fname << " " << MI << " " << lname << std::endl;
return 0;
}
Here for fname I have used std::getline to get user input and then I've used std::istringstream to get only one word of the input.
For MI I have made it a string and until and unless the user doesn't provide a single character, the program doesn't continue.
And the lname part is the same.
You should change:
cin.ignore(1, '\n');
cin.get(MI);
To simply:
cin >> MI;
Let operator>> ignore any white space, including line breaks, between the first name and the middle initial.
After reading MI, you can then use the following to ignore everything up to the next input:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Try this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main ()
{
string fname, lname;
char MI;
cout << "Please enter your first name: ";
cin >> fname;
cout << "Please enter your middle initial: ";
cin >> MI;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please enter your last name: ";
cin >> lname;
cout << "Your name is " << fname << " " << MI << " " << lname << endl;
return 0;
}
Related
I am writing a program that takes input from the user. I need the input to include spaces between the words. I am having trouble finding a solution to do that.
Before you ask, I have tried multiple other questions on StackOverflow with the same question. These are some of the ones I have tried:
How to cin Space in c++?
std::cin input with spaces?
Demonstration of noskipws in C++
Effect of noskipws on cin>>
The problem with my code is that as soon as my setBusinessName() method is called, it just completes itself. It outputs and then returns itself without waiting for me to input my data.
string setBusinessName()
{
string name = "";
cout << "The name you desire for your business:";
getline(cin, name, '\n');
cout << name;
return name;
}
I can't comment yet, don't have enough points, but did you try adding cin.ignore(); before the getline(cin, name, '\n'); ?
Like this:
string setBusinessName()
{
string name = "";
cout << "The name you desire for your business:";
cin.ignore();
getline(cin, name, '\n');
cout << name;
return name;
}
Just adding some more explanation to the comments, when you do:
cout << "Enter value:";
cin >> x;
The cin instruction is executed when the user presses Enter, so the input buffer has the value the user inserted and an extra '\n' char. If you continue doing cin that is ok, but if you want to use getline (like in your case to include spaces in a string) you must be aware that getline will stop at the first occurence of '\n' in the buffer, so the result from getline will be empty.
To avoid this, and if you really must use both cin and getline, you need to remove that '\n' from the buffer by using cin.ignore(streamsize n = 1, int delim = EOF), this function clears streamsize chars from the buffer or until the first char that matches delim (including), here's an example:
cin << x;
cin.ignore(256, '\n');
getline(cin, name, '\n');
Note it is advisable to use:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if you don't want to guess how many chars are in the buffer.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name1, name2, name3, name4, name5;
int a,b; //or float ...
cout << "Input name 1: ";
getline(cin, name1); //input: abc def
cout << "=> Name 1: "<< name1 << endl; //output: abc def
cout << "Input name 2: ";
getline(cin, name2); //input: abc def
cout << "=> Name 2: "<< name2 << endl; //output: abc def
cout<<"a: ";
cin>>a;
cout<<"a: "<<a<<endl;
cout << "Input name 3: ";
getline(cin, name3); //can not input
cout << "=> Name 3: "<< name3 << endl; //output:
cout<<"b: ";
cin>>b;
cout<<"b: "<<b<<endl;
cout << "Input name 4: ";
cin.ignore();
getline(cin, name4); //input: abc def
cout << "=> Name 4: "<< name4 << endl; //output: abc def
cout << "Input name 5: ";
cin.ignore();
getline(cin, name5); //input: abc def
cout << "=> Name 5: "<< name5 << endl; //output: bc def !!!!!!!!!!
//=> cin>>number; cin.ignore(); getline(cin, str); => OK
//else: !!!!!!!!
return 0;
}
It's possible that there is already something in the stream and getline() just reads it.
Make sure you didn't use cin>> before this function.
And you can use cin.ignore() before getline() to avoid something already existed in the stream.
It is working fine. I just tried this.
#include <iostream>
#include <string>
using namespace std;
string setBusinessName(){
string name = "";
cout << "The name you desire for your business:";
getline(cin, name);
cout << name;
return name;
}
int main() {
setBusinessName();
system("PAUSE");
}
#include<bits/stdc++.h>
using namespace std;
string setBusinessName(){
string name;
cout << "The name you desire for your business: ";
getline(cin, name);
cout << name;
return name;
}
int main() {
setBusinessName();
return 0;
}
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.
Here are my codes:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int age1;
int age2;
string name1;
string name2;
cout << "Please enter the name for one people: " << "\n";
getline (cin, name1);
cout << "Please enter the age for this people: " << "\n";
cin >> age1;
cout << "Please enter the name for another people: " << "\n";
getline (cin, name2);
cout << "Please enter the age for this people too: " << "\n";
cin >> age2;
if ( (age1 <= 100 || age2 <= 100) && (age1 < age2) )
{
cout << name1 << " is younger!" << "\n";
}
else if ( (age1 <= 100 || age2 <= 100) && (age1 > age2) )
{
cout << name2 << " is younder!" << "\n";
}
else if ( (age1 <= 100 || age2 <= 100) && (age1 = age2) )
{
cout << name1 << " and " << name2 << " are of the same age!" << "\n";
}
else
{
cout << "You've got some really old people that are well older than 100!";
}
}
The first getline and cin works fine. I am able to be prompted to input.
However, the second getline and cin are prompted at once, thus I can only input for cin. (The second getline is skipped!)
If I use four cins, the program will work properly.
cin >> age1; does not read the newline character following the number. The newline remains in the input buffer, then prematurely stops the second getline.
So, your program already works as long as you enter the first age and the second name on the same line.
One solution would be to skip whitespace after the numbers:
cin >> age1 >> ws;
Live demo.
first: cin>>age; It takes the number and stores into age but at the same
time it leaves the newline character in the buffer itself. so when there is prompt for next name cin finds that left over newline character in the buffer and takes it as the input. that it why it escapes the name2 prompt.
cout << "Please enter the name for one people: " << "\n";
cin>>name1;
cout << "Please enter the age for this people: " << "\n";
cin >> age1;<<--**this left the new line character in input buffer**
cin.get();<<-- **get that newline charachter out of there first**
cout << "Please enter the name for another people: " << "\n";
getline (cin, name2);
cout << "Please enter the age for this people too: " << "\n";
cin >> age2;
now i give name1-> shishir age1->28
name2->ccr age-> 22 it prints ccr is younder!<-- the spelling is wrong too :D
for more info on getline and get() read c++ primer plus listing 4.3, 4.4, 4.5
Happy coding
You need a ; after getline (cin, name);
hope this helps
I would suggest using cin.ignore(100,'\n'). It ignores the amount of characters you specify when you call it(100 in the example above), up to the char you specify as a breakpoint. For example:
cout << "Please enter the name for one people: " << "\n";
getline (cin, name1);
cout << "Please enter the age for this people: " << "\n";
cin >> age1;
cin.ignore(100, '\n');
cout << "Please enter the name for another people: " << "\n";
getline (cin, name2);
cout << "Please enter the age for this people too: " << "\n";
cin >> age2;
cin.ignore(100, '\n');
When I input "M12 9UB" to this code:
std::string postal_code;
cout << "Enter postal code: ";
cin >> postal_code;
cout << "Your postal code is: " << postal_code << endl;
The output is "Your postal code is: M12".
So how do I get cin to read the whole line?
Use std::getline to read a whole line from a stream:
std::getline(std::cin, postal_code);
Live example.
You may use the C++ getline function like so:
#include <iostream>
using namespace std;
int main()
{
std::string postal_code;
cout << "Enter postal code: ";
getline(cin,postal_code);
cout << "Your postal code is: " << postal_code << endl;
}
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...
}