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. Help Required...
string setBusinessName()
{
string name = "";
cout << "The name you desire for your business:";
getline(cin, name, '\n');
cout << name;
return name;
}
So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);
scanf() reads input until it encounters whitespace, newline or End Of File(EOF) whereas gets() reads input until it encounters newline or End Of File(EOF), gets() does not stop reading input when it encounters whitespace instead it takes whitespace as a string.
String variables contain strings of characters. The characters can be any printable character on the keyboard, including spaces and punctuation (but not function keys, the enter key, and some others.)
The isspace() function checks whether a character is a white-space character or not. If an argument (character) passed to the isspace() function is a white-space character, it returns non-zero integer. If not, it returns 0.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With