[英]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)。
// 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.