String Help

I have the following program and do not understand the error:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    int vowelCount=0, consCount=0;
    cout<<"This program will determine how many characters are vowels and how many characters and consinants"<<endl
        <<"Please enter a string: ";
    cin>>s;

    for(unsigned int i=0; i<s.length(); i++) {
        if(s[i]=="a") {
            /* Other code */
        }
    }
    cout<<"There are:"<<endl
        <<vowelCount<<" Vowels"<<endl
        <<consCount<<" Consinants";
    return(0);
}


C:\Users\Ex\Documents\Computing\Programming languages\C++\CodeBlocks\Vowel and Consinant\main.cpp||In function 'int main()':|
C:\Users\Ex\Documents\Computing\Programming languages\C++\CodeBlocks\Vowel and Consinant\main.cpp|13|warning: comparison with string literal results in unspecified behaviour|
C:\Users\Ex\Documents\Computing\Programming languages\C++\CodeBlocks\Vowel and Consinant\main.cpp|13|error: ISO C++ forbids comparison between pointer and integer|
||=== Build finished: 1 errors, 1 warnings ===|
Last edited on
Hi there,

Trying doing this at line 13:

if(s[i]=='a') //single quotes

Single quotes represent char-constants, double quotes represent string constants ( / literals).
As you can read here: http://cplusplus.com/reference/string/string/operator%5B%5D/
std::string[] returns a character, so comparing it to a string is not legal.

Hope that helps.

All the best,
NwN
Yes NwN is correct, also there were some semi colons missing, and cout sataements missing from the front of some of the << operators, also use getline(cin, s); instead of cin >> s, this way you can get an entire sentance instead of just one word. This code compiles.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    int vowelCount=0, consCount=0;
    cout << "This program will determine how many characters are vowels and how many characters and consinants" << endl;
    cout << "Please enter a string: ";
    getline(cin, s);

    for(unsigned int i = 0 ; i < s.length(); i++)
    {
        if(s[i] == 'a')
        {
            /* Other code */
        }
    }
    cout << "There are:" << endl;
    cout << vowelCount << " Vowels"<<endl;
    cout << consCount << " Consinants";

    return(0);
}
Last edited on
@ch1156 you can do the cout the way I have as it simplifies to:
cout<<"There are:"<<endl<<vowelCount<<" Vowels"<<endl<<consCount<<" Consinants";
@NwN Thanks it works
Last edited on
Really? i never knew that. Hmm learn something new every day.
Topic archived. No new replies allowed.