Reputation: 873
Okay, I was writing a simple C++ function to combine cin'd strings. I'm working on Linux at the moment, so I don't have the luxury of a simple "getline(cin, input)" command. Here's the code so far:
string getLine()
{
string dummy;
string retvalue;
do
{
cin << dummy;
retvalue += dummy;
} while
return retvalue;
}
What I want to know is this: is the prompt actually asking the user for input, or is it still reading from the buffer that was left over because of a space?
Upvotes: 0
Views: 886
Reputation: 3671
Yes. the prompt IS actually asking the user for input, but it is expecting a word rather than a line. That is possibly why it appeared space sensitive to you.
What you want, assuming you want to read more than one line, is this.
#include <iostream>
...
std::string sLine;
while(getline(std::cin, sLine)) {
// process sLine;
}
The code had a few other issues.
The loop in the question is closer to a word reader. This would do for that objective.
#include <string>
#include <iostream>
#include <list>
...
void getStandardInput(std::list<std::string> & stringList) {
std::string word;
while (true) {
cin >> word;
if (cin.eof())
return;
stringList.push_back(word);
}
}
Upvotes: 0
Reputation: 239930
I'm working on Linux at the moment, so I don't have the luxury of a simple "getline(cin, input)" command.
What's Linux got to do with it? getline
is standard C++, except it's spelled cin.getline(input, size[, delimiter])
.
Edit: Not deleting this because it's a useful reference, but AraK's post illustrating std::getline
should be preferred for people who want a std::string
. istream
's getline
works on a char *
instead.
Upvotes: 6
Reputation: 96879
There is a getline
defined for strings
:
std::string line;
std::getline(std::cin, line);
Upvotes: 8