Search code examples
c++filestreamgetline

Finding the words from a file which have character 'a' as a last letter


ifstream input;
string filename="file.txt";
string word;

input.open(filename.c_str());
int len=word.length();

while(getline(input,word)) {

    if(word.at(len-1)='a') {
        cout<<word;
    }

}

While I execute it,compiler gives a runtime error I do not understand why ? I want to find the words which have the last character as 'a' thanks


Solution

  • int len=word.length(); should be in the loop.

    Currently, len is 0.

    You also have a typo = (assignation) should be == (test for equality)

    Btw, since C++11, you may use word.back(). And you should check that string is not empty.

    Result to:

    while (getline(input, word)) {
        if (!word.empty() && word.back() == 'a') {
            std::cout << word;
        }
    }