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

后端 未结 3 476
无人及你
无人及你 2020-11-29 07:29
#include
...
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          


        
3条回答
  •  一向
    一向 (楼主)
    2020-11-29 08:22

    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
    #include
    ...
    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 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;
    

提交回复
热议问题