Search code examples
c++stringstlio

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


#include<string>
...
string in;

//How do I store a string from stdin to in?
//
//gets(in) - 16 cannot convert `std::string' to `char*' for argument `1' to 
//char* gets (char*)' 
//
//scanf("%s",in) also gives some weird error

Similarly, how do I write out in to stdout or to a file??


Solution

  • 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;