0

So I currently have a working programme which successfully finds and displays all the characters in an text file. I now want to be able to read whole words instead of characters and then want to store each word into an array but I have no idea how to even read whole words.

My current code for characters

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

int main()
{
    ifstream infile("input.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");
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
HeyHey
  • 9
  • 1

3 Answers3

2

I now want to be able to read whole words instead of characters and then want to store each word into an array but I have no idea how to even read whole words

std::string word;
infile >> word;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Change the type of ch to std::string so >> will read words.

FireRain
  • 103
  • 8
0

Use,

std::string word;
infile >> word;

Instead of,

char ch;
infile >> ch;
RLoniello
  • 2,309
  • 2
  • 19
  • 26