Accessing chars in a string

Hi there,

I'm having some trouble at the moment I believe with either accessing characters within a string or with comparing the character found with the expected character. I'll post the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  for (int i = 1; i<3599; i++) {
        getline (inputfile,line);
          for (int j = 0; j< line.length() ; j++){
            if (line[j]=='a'||'A'){
              anumber = anumber + 1;
          }
            else if (line[j]=='b'||'B'){
              bnumber = bnumber + 1;
          }
            else if (line[j]=='c'||'C'){
              cnumber = cnumber + 1;
          }
            else if (line.at(j)=='d'||'D'){
              dnumber = dnumber + 1;
          }
            else if (line.at(j)=='e'||'E'){
              enumber = enumber + 1;
          }
            else if (line.at(j)=='f'||'F'){
              fnumber = fnumber + 1;


This is just a sample of the oode. I have tried both line[j] and line.at(j). The program is intended to count the number of each characters within a text file, however currently it is counting all the characters as the character 'a'. Thanks for the help.
This won't work: if (line[j]=='a'||'A'){

You need to explicitly test each value,
if (line[j]=='a' || line[j]=='A'){

The program is intended to count the number of each characters within a text file,

If you need to extend this code to every possible character, the program could become very lengthy. You might want to consider other approaches, such as using tolower() to convert each character to lowercase, and perhaps use an array or a std::map for the accumulation.

http://www.cplusplus.com/reference/cctype/tolower/
Last edited on
closed account (48T7M4Gy)
http://www.cplusplus.com/reference/cctype/isalpha/?kw=isalpha
Topic archived. No new replies allowed.