tags:

views:

467

answers:

3

Hello,

Looking for a simple getline example which works correctly.

I want to input something on the keyboard and assign it to a std::string, allowing for whitespace and tabs. The delimiter is the carriage return.

TIA, Bert

+5  A: 
#include <string>
#include <iostream>
#include <ostream>

int main() {
  std::string s;
  std::cout << "Enter a line: ";
  std::getline(std::cin, s);
  std::cout << "You typed this: " << s << std::endl;
  return 0;
}

Example run:

$ ./a.out
Enter a line: foo bar
You typed this: foo bar
Rob Kennedy
You don't need #include <ostream>
anon
I thought it was technically required for operator<<, no?
Rob Kennedy
iostream pulls in most of the required stuff :)
OregonGhost
@rob you would #include <ostream> if you wanted the output operators but didn't need cin, cout et al. As cout is an ostream, iostream must include <ostream> itself.
anon
+1  A: 

An important note: after you use std::cin:

cin >> myVar;

The trailing newline is NOT removed. You have to use getline twice

std::getline(std::cin, myString);
std::getline(std::cin, myString);

if you have previously extracted from cin, once for the newline, and once for the actual string. There are other ways to do this too.

rlbond
But also note: cin >> ignores proceeding whitespace so it would not be affected by the newline.
Martin York
A: 

Thank you rlbond, that was exactly the problem I was encountering. You post helped me fix the bug.

Why is that ?

Cheers, Bert

so why not accept the answer?
anon