Printing from file one word at a time.

closed account (j8CjE3v7)
I have done an exercise from "Thinking in C++" to print text from a file to the console one line at a time, with the user pressing enter to get the next line.

My original code is below, how could I change it for one word at a time?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main() {

ifstream in("MIB.txt");

string word;

while (in.good()) {
getline(in, word);
cout << word;
cin.get();
}
cin.get();
}

I tried to alter my program to print one word at a time by changing "getline(in, word)" to "in >> word", but it prints each new word on a new line, the only input I have found to make the next word appear is Enter, I assume that's why.

Is there a way to make it print one word at a time when the user says, but on the same line?
Last edited on
Use
1
2
3
4
5
6
7
string word;

while (in.good())
{
    in >> word; // get one word from the file
    cout << word << endl;  // print the word and a new line
}
closed account (j8CjE3v7)
Thanks for the reply, I don't think my question is clear. It is printing each word on a new line, I was wondering if you can print it on the same line. I will edit the post.
To print on the same line, just don't use endl;

1
2
3
4
5
6
while (in.good())
{
    in >> word; // get one word from the file
    cout << word << " ";  // print the word and a space so words don't merge
}
cout << endl; // finished printing, now go to a new line 


Hope that helps.
closed account (j8CjE3v7)
Works better now thanks.
Topic archived. No new replies allowed.