gpt4 book ai didi

c++ - while 循环不输出子字符串的下一个实例

转载 作者:行者123 更新时间:2023-11-30 03:57:26 25 4
gpt4 key购买 nike

我有以下代码

#include <iostream>
#include <fstream>
#include <string>

int main(){
std::string file = "words.txt";
std::string word;
std::ifstream inFile;
std::string delimiter = ",";
inFile.open(file);
if (!inFile){
std::cerr << "File not opened." << std::endl;
}
while (getline(inFile, word)){
std::cout << word.substr(0, word.find(delimiter)) << " ";
word.erase(0, word.find(delimiter) + delimiter.length());
}
inFile.close();
std::cin.get();
}

这个循环有问题:

    while (getline(inFile, word)){
std::cout << word.substr(0, word.find(delimiter)) << " ";
word.erase(0, word.find(delimiter) + delimiter.length());
}

我收到的唯一输出是 "word1" 形式的第一个子字符串在输出中。

我输入了 std::cout << word.substr(0, word.find(delimiter))在删除函数之后的行中确定单词是否仍然有字符,确实如此。 word是一个很长的字符串,格式为 "word1","word2","word3",...,"lastword"我的分隔符是 "," .

最佳答案

作为@Joseph Mansfield评论里说。您正在遍历文件行而不是其中的单词。

要按, 拆分单词,您可以简单地使用定界符作为getline 的第三个输入。

#include <iostream>
#include <fstream>
#include <string>

int main(){
std::string file = "words.txt";
std::string word;
std::ifstream inFile;
char delimiter = ',';
inFile.open(file);
if (!inFile){
std::cerr << "File not opened." << std::endl;
}
while (getline(inFile, word,delimiter)){
std::cout << word << " ";
}
inFile.close();
std::cin.get();
}

阅读多行:

std::string line;
while (getline(inFile, line)){
std::stringstream stream(line);
while (getline(stream, word, delimiter)){
std::cout << word << " ";
}
}

关于c++ - while 循环不输出子字符串的下一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27989368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com