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;
}
Related
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;
}
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.
Why does my code not run properly? As soon as it gets to the if else statement it takes one input from the user and then exits before I can enter anything else. I am not sure if it is due to the function not returning properly but I would really appreciate some help. Thanks.
#include <iostream>
#include <fstream>
using namespace std;
void studentenrollment (char answer);
int main()
{
char answer; //declaring variables for main
cout << "Welcome to Luton Sixth Form" << endl; //greeting the user
cout << "Please State if you are enrolled or not at the sixth form: Y/N" << endl;//giving user options
cin >> answer;//taking options from user
studentenrollment(answer); //calling student enrollment function
return 0;
}
void studentenrollment (char answer)
{
unsigned char name;
int dob;
if (answer=='Y'||answer=='y')
{
cout << "Welcome to higher education" << endl;
cout << "Please state your name" << endl;
cin >> name;
ofstream myfile;
myfile.open("StudentAccess.txt");
myfile << name << endl;
myfile.close();
cout << "Your name is now saved, you have access to the gateway" << endl;
}
else if(answer=='N'||answer=='n')
{
cout << "Please state your name" << endl;
cin >> name;
cout << "Please enter your date of birth" << endl;
cin >> dob;
ofstream myfile;
myfile.open("StudentEnrollment.txt");
myfile << name << dob << endl;
myfile.close();
cout << "You will now go through enrollment" << endl;
}
// return 0;
}
unsigned char name; looks incorrect. Choose char name[MAX_LENGTH]; or std::string name;
What happens
cin >> name; // Read just first character
cin >> dob; // Try to read number, where rest of the name is left in the stream buffer
This certainly looks wrong unless the name is 1 letter wide.
Problem can be this:
cin >> name;
you are entering name but storing it in name - which is just unsigned char. Use a larger array to store the name.
If the variable name can contain more than 1 character you cannot declare it unsigned char, you can declare it std::string. remember the
#include<string>
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...
}
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);