解析并将字符串添加到向量 [英] Parsing and adding string to vector
问题描述
我有以下字符串"0 1 2 3 4"(字符串末尾有一个空格).我想拆分并添加到字符串向量中.当我使用一个循环和一个字符串流时,该程序将其自身循环成最后一个数字为4的无限循环.它不想停止.
I have the following string "0 1 2 3 4 "(There is a space at the end of the string). Which i would like to split and add to a vector of string. When i use a loop and a stringstream, the program loops itself into a infinity loop with the last number 4. It does not want to stop.
如何拆分以下内容并同时添加到字符串向量中.
How can I split the following and add to a vector of strings at the same time.
请提前.
stringstream ss(currentLine);
for(int i=0;i<strlen(currentLine.c_str());i++){
ss>>strCode;
strLevel.push_back(strCode);
}
推荐答案
std::ifstream infile(filename.c_str());
std::string line;
if (infile.is_open())
{
std::cout << "Well done! File opened successfully." << std::endl;
while (std::getline(infile, line))
{
std::istringstream iss(line);
std::vector<std::string> tokens { std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() };
for (auto const &token : tokens)
if (!token.compare("your_value"))
// Do something....
}
}
首先,我们仅使用std::istringstream iss(line)
读取一行,然后根据空格将单词拆分并将其存储在tokens
向量中.
First of all, we read a line just by using std::istringstream iss(line)
, then we split words according to the whitespaces and store them inside the tokens
vector.
更新:感谢Nawaz提出的改进建议(请参阅评论).
Update: thanks to Nawaz for improvement suggestions (see comments).
这篇关于解析并将字符串添加到向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!