Lolings Brown
Lolings Brown

Reputation: 25

How to read words instead of characters?

I am currently trying to read a bunch of words from a .txt document and can only manage to read the characters and display them yet. I'd like to do the same but with whole words.

My code:

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

int main()
{

ifstream infile("banned.txt");
if (!infile)

{

    cout << "ERROR: ";
    cout << "Can't open input file\n";

 }

 infile >> noskipws;
 while (!infile.eof())
 {
    char ch;
    infile >> ch;

    // Useful to check that the read isn't the end of file
    // - this stops an extra character being output at the end of the loop
    if (!infile.eof())
    {
        cout << ch << endl;
    }
 }
system("pause");
}

Upvotes: 0

Views: 109

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Change char ch; to std::string word; and infile >> ch; to infile >> word; and you're done. Or even better do the loop like this:

std::string word;
while (infile >> word)
{
    cout << word << endl;
}

Upvotes: 2

Related Questions