new123456
new123456

Reputation: 873

C++ cin Question

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

Answers (4)

user8210143
user8210143

Reputation: 50

getline() is in the <string> header

I always forget that.

Upvotes: 0

Douglas Daseeco
Douglas Daseeco

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.

  • cin << dummy // this should have the >> operator
  • The variable should probably be called "word" not "dummy"
  • retvalue += dummy; // you would need to add spaces between words
  • } while // the while test should be some test for end of line

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

hobbs
hobbs

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

Khaled Alshaya
Khaled Alshaya

Reputation: 96879

There is a getline defined for strings:

std::string line;
std::getline(std::cin, line);

Upvotes: 8

Related Questions