到达分隔符时跳到文本文件的下一行

Skipping to next line of text file when delimiter reached

本文关键字:一行 文件 分隔符 文本      更新时间:2023-10-16

我有一个while(inFile >> word){循环和一个 10 行的文本文件:

交易品种指令 #123, $456 ;一堆评论

我的问题是,我怎么能忽略分号后面的任何内容并跳到下一行?本质上

if(word.find(";"))
{
//move along
}

使用不同的方法 - 首先阅读整行,然后在;后去除注释,然后使用其余行。

std::string line;
while (std::getline(infile, line)) {
const auto commentStart = line.find(';');
if (commentStart != std::string::npos)
{
line.erase(commentStart); //strip comments
}
... //use the line somehow
}

如果您想在阅读行后有单独的单词,您可以使用例如std::stringstream(但有许多不同的选择(:

std::stringstream ss(line);
std::string word;
while(ss >> word) {
//use single word
}