Search code examples
c++stringstring-length

Why do I get zero length for a string filled element by element?


this is my issue. I am compiling with g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0

I would like to check every element of the string, and copy it only if it is a consonant.

This is how I try to do that: This is just a function to select vowels:

bool _is_vowel(char a){
    if (a=='a' || a=='A' || a=='e' || a=='E' ||a=='i' || a=='I' || a=='o' || a=='O' || a=='u' || a=='U' || a=='y' || a=='Y')
        return true;
    else return false;
}

This is the bit of code that does not work. Specifically, inside the ss.length() appears to be 0, and the string ss contains no character, but they are correctly printed inside the while loop.

 main(){
    int i=0, c=0; 
    string ss, name;
    cout << "insert name\n";
    getline(cin, name);
    while (i<int(name.length())){
       if (!_is_vowel(name[i])){
          cout << name[i]<< "\t";
          ss[c]=name[i];
          cout << ss[c]<< "\n";
          c++;
        }
        i++;
    }    

    cout << int(ss.length())<<endl;
    cout << ss;                
    } 

Could anyone explain to me where I am wrong or give me some reference? Thank you in advance


Solution

  • string ss;
    

    Declares a string of length 0.

    ss[c] = ...;
    

    Then tries to access and set to an index that doesn't exist. This is Undefined Behavior. If you had used .at() which does bounds checking, you would've caught this immediately.

    To fix this, you can either append to the string with the += operator:

    ss += name[i];
    

    Or you can use push_back():

    ss.push_back(name[i]);
    

    Furthermore, instead of checking every. single. character, I'd strongly suggest taking a look at this answer for a better way.