Aisha Ahmed Ahmed
Aisha Ahmed Ahmed

Reputation: 108

Read text file char by char instead of word by word?

I tried to make a code that reads from text file called aisha

This is a new file I did it for as a trial for university
but it worked =)
Its about Removing stopwords from the file
and apply casefolding to it
It tried doing that many times
and finally now I could do now

and then the code stores the read text on an array and then removes the stopwords from it but now I nead to make the case folding step the problem that this code reads the text file word by word

I want to read it char by char so I can apply casefolding to each char is there ant way to make the code read the aisha file char by char ?

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    using namespace std;

    ifstream file("aisha.txt");
    if(file.is_open())
    {
        string myArray[200];

        for(int i = 0; i < 200; ++i)
        {
            file >> myArray[i];

            if (myArray[i] !="is" && myArray[i]!="the" && myArray[i]!="that"&& myArray[i]!="it"&& myArray[i]!="to"){
            cout<< myArray[i]<<"  ";
            }


        }
    }
system("PAUSE");
return 0;
}

Upvotes: 2

Views: 792

Answers (3)

user3050633
user3050633

Reputation: 35

Use Whole string instead of reading char by char using readline function.

Upvotes: 0

turnt
turnt

Reputation: 3255

The C++ way to do this is explained at this link: http://www.cplusplus.com/reference/istream/istream/get/

#include <iostream>     // std::cin, std::cout
#include <vector>       // store the characters in the dynamic vector
#include <fstream>      // std::ifstream

int main () {

  std::ifstream is("aisha.txt");     // open file and create stream
  std::vector <char> stuff;

  while (is.good())          // loop while extraction from file is possible
  {
    char c = is.get();       // get character from file
    if (is.good())
      std::cout << c;        // print the character
      stuff.push_back(c);    // store the character in the vector
  }

  is.close();                // close file

  return 0;
}

Now you basically have every character of the file stored in the vector known as stuff. You can now do your modification to this vector, for it is a far easier internal representation of data. Also, you have access to all the handy STL methods.

Upvotes: 1

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

If you declare your array as an array of char instead of array of strings, the extraction operator shall automatically read char.

Also you will have to be careful because the >> operator by default skips the whitespace characters. If you want to read the whitespaces also, then you should add noskipws before reading the characters.

file >> std::noskipws;

Upvotes: 2

Related Questions