Problem with first character of a char variable

Hello!

I need to count the number of times vocals appers in a text, but when I do this with the following code, it takes the first character as null (or at least that's what I concluded since the condition in the while loop is false from the very beginning if I declare c[0] = text[0]). Also, when I try to print text[0] on the screen, it only displays a blank space. My code looks like this:

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
33
34
35
36
37
#include<iostream>
#include<string.h>

using namespace std;

int main(){

char text[200] = "The bright sun was extinguished and the stars Did wander darkling in the eternal space, Rayless and pathless, and the icy earth Swung blind and blackening in the moonless air.";

char charact[] = "AaEeIiOoUu";
char c[2];
int numar[9];
int j;

for (int i = 0; i < 10; i++)
    numar[i]=0;

int i = 0;
// it does work from the second character though i.e. int i = 1;

while (c[1] != '\0'){
     c[1] = text[i];

//for (i = 0; text[i] != '\0'; i++)
    for (j = 0; j<10; j++){
        if (c[1] == charact[j])
            numar[j]++;}
    i++;
}


for (int i = 0; i < 10; i++){
    cout<<charact[i]<<" - "<<numar[i]<< endl;
}

return 0;
}


Can anyone explain why this happens? Thanks in advance
Last edited on
The size of the array numar is 9 not 10. I.e. i < 10 will go out of bounds and the result is an undefined behavior.

The array c makes no sense. Use the for loop on line 24 instead.
Topic archived. No new replies allowed.