[英]How to read in the third word of c++ stringstream
我收到了一份文件,我需要从中读取某些重要信息到我的 C++ 程序中。 这些信息以下列格式给出:
关键字:VALUE_OF_KEYWORDS_TYPE
其中VALUE_OF_KEYWORDS_TYPE通常包含一个 integer 值。 我使用以下方案将此值读入我的程序:
int variable_to_store_value = 0;
std::string content_of_line = "";
std::getline(file,content_of_line);
std::stringstream stream(content_of_line);
std::string threshold;
stream >> threshold >> threshold >> variable_to_store_value ;
使用阈值变量对我来说似乎有点可扩展,但我不确定解决这个问题的最正确方法是什么......另外让我知道,如果在这些事情的运行时间方面有更有效的方法。 非常感谢您尝试帮助我解决我的问题!
使用
threshold
变量对我来说似乎有点可扩展,但我不确定解决这个问题的最正确方法是什么......
我建议完全摆脱threshold
变量,而是使用stream.ignore()
方法来跳过你不想要的东西,例如:
#include <sstream>
#include <string>
#include <limits>
std::string content_of_line;
if (std::getline(file, content_of_line)) {
std::istringstream stream(content_of_line);
stream.ignore(std::numeric_limits<std::streamsize>::max(), ':');
int variable_to_store_value = 0;
if (stream >> variable_to_store_value) {
// use variable_to_store_value as needed...
}
}
或者,您也可以去掉stream
变量:
#include <limits>
if (file.ignore(std::numeric_limits<std::streamsize>::max(), ':')) {
int variable_to_store_value = 0;
if (stream >> variable_to_store_value) {
// use variable_to_store_value as needed...
}
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.