I'm trying to do a simple while loop that searches a string for a specific character then returns each place the character appears in the string before ending the loop
Here is a version of my code, where I have been trying to catch when the point where the number is no longer either 0, or less than the length of the string, as I couldn't get the while loop to end without the if statement, I tried adding it in to force 'num' to be outside these bounds and see if the while loop conditions would catch it and end the loop, seemingly not.
#include <iostream>
using namespace std;
int main() {
string phrase = "Hello I am a pineapple";
int phraseLength = int(phrase.length());
int num = 0;
while(num < phrase.length() -1 && num > -1)
{
num = int(phrase.find('a', num));
cout << num << endl;
num++;
if(num < phraseLength -1 || num ==0){
cout << num << endl;
}else{
num = 24;
}
}
I'm more used to python and currently trying to learn c++, I know if I were to use these conditions in python, the loop would end, so why not here?
Sample output:
9
11
12
17
18
-1
0
8
9
11
12
17
18
-1
0
8
9
11
12
17
18
-1
0
8
9
11
12
17
18
-1
0
8
9
11
12
17
18
-1
0
8
9
11
12
17
18
-1
0
8
9
11
12
17
18
-1
0
8
9
11
12
17
18
-1
0