简体   繁体   中英

Unable to read each word in a text file

I have got a text file with contents:

Artificial neural networks (ANNs) or connectionist systems are computing systems vaguely inspired by the biological neural networks that constitute animal brains.[1] Such systems "learn" (ie progressively improve performance on) tasks by considering examples, generally without task-specific programming. For example, in image recognition, they might learn to identify images that contain cats by analyzing example images that have been manually labeled as "cat" or "no cat" and using the results to identify cats in other images. They do this without any a priori knowledge about cats, eg, that they have fur, tails, whiskers and cat-like faces. Instead, they evolve their own set of relevant characteristics from the learning material that they process.

and I'm using this code to read the contents.

ifstream file("/Users/sourav/Desktop/stl/stl/stl/testdata.txt");
while (! file.eof()) {
    string word;
    file >> word ;
    cout << word << "\n";
}

This is the first few lines of output:

Artificial

neural

(ANNs)

are

vaguely

and if you notice that the contents are not read properly. I don't see or connectionist systems are computing systems .

I'm missing few string values from the text file while reading it.

Note:I'm using Xcode.

ifstream file("/Users/sourav/Desktop/stl/stl/stl/dictionary.txt");
string line;

if (file.is_open())  // same as: if (myfile.good())
{

    while(getline(file,line,'\r')){
         transform(line.begin(), line.end(), line.begin(), ::tolower);
        Dictionary.insert(line);


    }
    cout<<Dictionary.size()<<" words read from dictionary\n";
    file.close();

Why does the dictionary.size() change in value when I transform it to lowercase

Try using something along the lines of this:

ifstream file("/Users/sourav/Desktop/stl/stl/stl/testdata.txt");

string word;
while(file >> word) //While there is a word to get... get it and put it in word
{
    cout << word <<"\n";
}

A little bit more of an explanation can be found on the accepted answer in question read word by word from file in C++

I don't see much of a difference in logic though between this and your logic.

While this may not explain why it does not work, your code may look like:

ifstream file("testdata.txt");
do {
  string word;
  file >> word ;
  if (!file.good()) break;
  cout << word << "\n";
} while (!file.eof());

It is not correct to test for eof condition if you never tried to read something first.

This code (and yours while being logically incorrect) works perfectly. So something else is happening (that is not related to xcode ).

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