简体   繁体   中英

Reading Third Word of File Input (C++)

So I am doing a practice exam for one of my classes, but I'm stuck as to how to solve the problem. We are given the following C++ code:

#include <iostream>
#include <fstream>

using namespace std;
int main​() {
ifstream infile("princes.txt");
string s;

while(________________)
{
    cout << s << endl;
}
    cout << endl;
    return 0;
}

And where the ________ is, we are supposed to fill in code to properly generate the desired output. We are not allowed to modify the code besides the underscored area. The file we are reading in from called "princes.txt" and the desired output are:

"Princes.txt"
Prince of Persia
Prince of Wales
Prince of Bel-Air
Prince of Egypt

Desired Output:
Persia
Wales
Bel-Air
Egypt

I'm stuck on how to only read the third word of each line using only the underscored area. I know how to read the whole line with getLine or three separate Strings where we could just output the third String each time, but since we're not allowed to modify anything else, I'm lost.

How about:

while(infile>>s && infile>>s  && infile>>s)

which could clobber the first 2 s values?

while(!(infile.eof())|| ++ x%3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM