fstream, string class; inputting strings from file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
#include<string>
#include<fstream>
#include<cstdlib>
using namespace std;
int main()
{
int n=0, count=0;
ifstream inFile("hey.txt");
string line;
   while (inFile.good())
      {
        inFile >> line;
        if(line=="END")
      {
        system("PAUSE");
      }
             while(line.length()>=n)
                {
                   if(line[0]==line[n])
                {
                     count++;
                     n++;
                }
                     else
                     n++;
                }
                     cout << count << endl;
                }
system("PAUSE");
return 0;
}


this program reads a string input from a file and outputs the number of characters that are the same letter as the first letter of that string.

ex: "aardvark"
would display "3".
the first letter is 'a', and 'a' appears 3 times in aardvark.

for some reason, it only works for the first string and all subsequent strings display the same number.

thanks
This looks like a homework assignment, so all I will say is:

#include<cstdlib> is not being used for anything here.

getline is very good at getting lines. Read about it.

(line[0]==line[n])

This is comparing the first character of the string to the rest of the string. You want to be comparing a to the rest of the string, not whatever the first character has to be.

You don't reset your count ? Unless you want a cumulative answer.
Topic archived. No new replies allowed.