Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to display the accurate word after other word, which has 8 characters. Unfortunately there shows an error about string subscript out of range. I know that the problem is with the loop, but I don't know how to solve it. Why "line[j] != '('" dosen't work?

getline(myFile, line);
size_t pos = line.find(arrayTypeOne[i]); //finding position
if (pos != string::npos)
{
    for (int j = pos + 9; line[j] != '('; j++)
        cout << line[j];
}//if

I solved it. The problem was in different place. I'm so sorry, I'll think twice next time. Thanks for help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
194 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is a possible chance that there is no '(' in the string. In this case, you keep incrementing the j variable without checking if the j variable has gone past line.length().

I suggest adding an and condition where you check if j is past the length of the string.

Edit 1: Searching again Can you avoid the loop and use:

line.find('(', pos + 1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...