#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
同样,如何将 in
写入标准输出或文件??
最佳答案
您正在尝试将 C 风格的 I/O 与 C++ 类型混合。使用 C++ 时,您应该使用 std::cin
和 std::cout
用于控制台输入和输出的流。
#include <string>
#include <iostream>
...
std::string in;
std::string out("hello world");
std::cin >> in;
std::cout << out;
但是在读取字符串时,std::cin 会在遇到空格或换行时立即停止读取。您可能想使用 std::getline
从控制台获取整行输入。
std::getline(std::cin, in);
您对文件使用相同的方法(在处理非二进制数据时)。
std::ofstream ofs("myfile.txt");
ofs << myString;
关于c++ - 如何读写 STL C++ 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2616968/