0

So I have been trying to make a simple program to count how many "au" there is in a text. Ran into a problem when everything seems working, except that it stops counting after the first row.

Here's the program:

#include <iostream>
#include <fstream>

using namespace std;

int au ();

int main(){

cout << au() <<endl;

return 0;
}

int au ()
{
    ifstream in("duom.txt");

    char a='a';
    char u='u';

    int n=0;

    char t, t1;

    while (!in.eof())
    {
        in.get(t);
        in.get(t1);
        if (t==a&&t1==u) n++;
    }
    in.close();
    return n;
}

photo to see results

  • Think about what your code would count if the input were, for instance, "tauras". – molbdnilo Feb 09 '21 at 13:45
  • 1) Related: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) 2) "_except that it stops counting after the first row._" How do you know that? Have you **stepped through** your code with a debugger? 3) Why not, simply, `std::getline` in conjunction with `std::string::find`? – Algirdas Preidžius Feb 09 '21 at 13:47
  • what does the input "duom.txt" contains ? and what you got as result ? – Jaziri Rami Feb 09 '21 at 13:48
  • for now it just contains short random text, I will edit question and add a photo. – Tauras Paliokas Feb 09 '21 at 13:59
  • 3 times auk in file... what other output would you expect?? – ΦXocę 웃 Пepeúpa ツ Feb 09 '21 at 14:05
  • well, there are more "au" in the file, there are 3 "au" in first row – Tauras Paliokas Feb 09 '21 at 14:07
  • I expect getting an output of 8 – Tauras Paliokas Feb 09 '21 at 14:08
  • How do you know that your program is counting the "au"s in the first row? There is no way for you to tell which ones were counted and which ones weren't. Use smaller, more systematic test data. (The problem is that you read two characters at a time, so you will find nothing in "Tauras", and if the input has an odd number of characters, your last read will fail with unpredictable results.) – molbdnilo Feb 09 '21 at 14:10

1 Answers1

0

The simple answer is that you read 2 chars at time (the 2 in.get() ) so basically are reading the file this way:

given abcaud in the file, you read ab ca ud

edit for clarification:
the problem is that while reading the file, you read 2 chars, check if they matched an then read the next ones. This way you read chars at position 0 and 1, then 2 and 3 and so on while you should reading the chars at position 0 and 1, then 1 and 2 and so on. If you check, you will discover that you find the string au only for the occurrences that has the a in a even position.

Using the example I give you above,

you read
ab ca ud
while it shoudl be
ab bc ca au ud

Gianluca
  • 2,831
  • 2
  • 32
  • 28