【发布时间】:2020-05-22 00:46:42
【问题描述】:
我的老师给了我这个作业,我需要从文件中读取单词,然后用它们做一些事情。我的问题是这些词必须以"hhh"结尾,例如:groundhhh、wallhhh等。
在寻找一种方法时,我想出了getline 库中的getline 函数。问题是 getline(a,b,c) 使用 3 个参数,其中第三个参数是读取直到找到 c 但 c 必须是 char,所以它对我不起作用。
本质上,我想要实现的是从文件中读取一个单词,例如"egghhh",并使其如此,如果读取"hhh",则意味着该行在那里完成,我收到"egg"作为这个词。我的老师用“哨兵”这个词来描述这个hhh的东西。
这是我的尝试:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream read_archive;
void showListWords(){
string word;
string sentinel = "hhh";
while (getline(read_archive,word,sentinel)){
cout << word << endl;
}
}
void openReadArchive(){
read_archive.open("words.txt");
if(read_archive.fail())
cout << "There is something wrong with the archive" << endl;
}
【问题讨论】: