c++ - 如何读写 STL C++ 字符串?

标签 c++ string stl io

#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::cinstd::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/

相关文章:

c++ - boost install windows msvc 10.0 -- example.cpp 链接失败

c++ - 为命名空间中定义的类重载 ostream 运算符 (<<)

c# - 如何正确地将 .NET 字符串编码为 native 代码的 std::wstrings?

java - String 在 Java 中如何成为引用类型?

C 模拟到 STL

c++ - std::map :使用自定义运算符时更新 key

c++ - DBL_MIN 是最小的正 double 吗?

c++ - VTK:在渲染窗口中启用分屏

java - 使用 args 的回文;帮我找出错误?

c++ - 当它们被定义为静态变量作为类成员时如何初始化STL映射