How to read and write a STL C++ string?

You are trying to mix C style I/O with C++ types. When using C++ you should use the std::cin and std::cout streams for console input and output.

#include <string>
#include <iostream>
...
std::string in;
std::string out("hello world");

std::cin >> in;
std::cout << out;

But when reading a string std::cin stops reading as soon as it encounters a space or new line. You may want to use std::getline to get a entire line of input from the console.

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

You use the same methods with a file (when dealing with non binary data).

std::ofstream ofs("myfile.txt");

ofs << myString;

Leave a Comment