在 C++ 中将 IFstream 与字符串而不是文件一起使用

use ifstream with a string instead of a file in c++?

本文关键字:文件 一起 中将 C++ IFstream 字符串      更新时间:2023-10-16

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 .