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
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
#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
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.
Thank you rlbond, that was exactly the problem I was encountering. You post helped me fix the bug.
Why is that ?
Cheers, Bert