Strings

Can anyone tell me what I am doing wrong here? I can find the first 'a' but I cannot seem to find the second 'a'. I know the code is very bad. How would I find the second 'a'? My idea is to find the first 'a' and from define it as 'int n' and from n+1 to s.length() to find the second 'a'. Am I doing this wrong?

Edit: Ok I realized that I cannot define j=n+1 that way because it wont save n from the first loop. Tried the binary scope operator :: but it gave the same results (sorry if that was a stupid idea but I dont know what to do)

1
2
3
4
5
6
7
8
9
10
11
12
13

int n=0;
 int main() {

	string s("Hello world i am back again");

	for (int i = 0; i <= s.length();i++) {
		int n = s.find('a');
	}

	for (int j = n+1; j<s.length();j++) {
		cout << s.find('a') << endl;
	}


Last edited on
Lifetime and masking.

You have int n on line 2. On global scope. Accessible from all lines 3-13.

Except on line 8. On line 8 you have a different int n. In local scope of loop's body.
A new n is created on every iteration and destroyed by line 9.

Line 8 does not change the n of line 2. Line 11 sees only the n of line 2.

Automatic variable exists only to the end of the scope where it is declared.
Name introduced in inner scope masks (hides) the (same) name of outer scope.


That is not all. On line 7 you do loop one past the end. Not that it matters, for you do nothing with the i.


What does the std::string::find do?
http://www.cplusplus.com/reference/string/string/find/

Notice that the find() takes two arguments. When you write s.find( 'a' ), the actual function call is s.find( 'a', 0 ).
Topic archived. No new replies allowed.