对于我的程序,我们应该读取一个文本文件并将其打印到屏幕上。在文本文件中,消息可能如下所示:
#email
mailservice
birdman
Intro
Hello Birdman! Welcome!
#email
Frank
birdman
Hello
Hello Birdman, how are you?
我需要跳过#email,以便打印出来:
From: mailservice
To: birdman
Subject: Intro
Message: Birdman! Welcome!
From: Frank
To: birdman
Subject: Hello
Message:Hello Birdman, how are you?
这是我的代码:
std::string filename1 = GetInboxFile(username);
std::ifstream fin(filename1);
std::string word;
std::cout << "\n";
std::string formatted = FormatEmailString("From: ", "To: ", "Subject: ", "Message: ");
//FormatEmailString is a function
std::cout << formatted;
while (fin.eof() == false)
{
std::string line = GetLine(fin);
if (fin.eof() == false)
{
std::cout << line << std::endl;
}//END IF STATEMENT
}//END WHILE LOOP
std::cout << std::endl;
fin.close();
答案 0 :(得分:1)
while (fin)
{
std::string line = GetLine(fin);
if (fin) // @DietmarKühl: checking if the input was successful
{
// if (line.find("#email") != std::string::npos)
if(line == "#email\n")
{
line = "\n"; // you want a empty line instead
// continue; // you could use continue to simply skip it
}
std::cout << line << std::endl;
}
}
答案 1 :(得分:1)
如果输入文件只包含有效数据,而我们不需要检查它,那么我们可以按如下方式获得正确的输出:
while (getline(fin, lineFromFile)) {
if (lineFromFile.find("#email") < 40000) {
getline(fin, lineFromFile);
cout<<"From: "<<lineFromFile<<endl;
getline(fin, lineFromFile);
cout<<"To: "<<lineFromFile<<endl;
getline(fin, lineFromFile);
cout<<"Subject: "<<lineFromFile<<endl;
getline(fin, lineFromFile);
cout<<"Message: "<<lineFromFile<<endl<<endl;
}
}