在 C++ 中将 IFstream 与字符串而不是文件一起使用
use ifstream with a string instead of a file in c++?
ifstream
有很好的工具来解析文件,例如在循环中工作的<<
,可以将浮点数、整数或任何您想要的变量消耗到变量中(只要您的变量类型与您尝试使用<<
的内容相匹配。我想知道是否,而不是:
ifstream myReadFile;
myReadFile.open(some_file); // open the file
float x;
int y;
// some_file = "0.5 5"
myReadFile >> x >> y;
如果我能以某种方式获得一个与some_file相同的字符串对象进入 ifstream。我想做的是:
ifstream myReadFile;
myReadFile = my_string
...
本质上,使用 ifstreams 解析文件很容易,但在 c++ 中解析字符串是一个 PITA(与 Python 相比)。
使用 std::stringstream
:
// Initialize contents of the stream with your string
std::stringstream myReadString(my_string);
float x;
int y;
// Use the stream just like an fstream
// my_string = "0.5 5"
myReadString >> x >> y;
呃,你可能想看看stringstream
.
相关文章:
- 将 getline() 与文件一起使用
- 与clang++一起使用的VS代码在构建良好的C++文件中显示错误
- 我应该如何获取配置文件的绝对路径与 Windows .exe一起发布?
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 无法使包含.hpp文件与其中的2个文件一起使用
- 您是否必须随项目一起交付原型文件?
- 将boost::filtering_streambuf与newline_filter一起使用时为空文件
- 有没有办法将 getline() 与外部文本文件一起使用,然后重新获得 cin 的控制权以从控制台获取输入?
- 如何制作一个与.txt文件一起使用的C 程序而不显示
- 将qresource qfile与文件一起使用
- 如何将boost::iostreams::mapped_file_source与gzip输入文件一起使用
- 在 C++ 中将 IFstream 与字符串而不是文件一起使用
- argv 和 argc 与输入/输出文件一起使用
- Visual Studio 2012将项目模板与文件一起导出
- 将HeaderDoc与.hpp文件而不是.h文件一起使用
- 使头文件与.cpp文件一起工作
- 试图与可执行文件一起使用gdb时出现问题
- 如何将fltk文件与其他文件一起编译
- 在带有Rcpp的R包中,将头(.h)文件与cpp文件一起使用
- rand()函数不能与文件I/O一起工作