coming from python this would seem like valid code, but it gives warnings and "-fpermissive g++ will accept your code"
So i am assuming there must be a better way. I am just not sure what it is.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <string>
usingnamespace std;
int main(){
string s = "test";
for (int i=0; i < s.length(); i++)
cout << s[i] << endl;
if (s[i] == 'e')
cout << "found e" << endl;
}
1 2 3 4 5
metulburr@ubuntu:~$ g++ test.cpp -o main
test.cpp: In function ‘int main()’:
test.cpp:11:9: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
test.cpp:11:9: note: (if you use ‘-fpermissive’ G++ will accept your code)
metulburr@ubuntu:~$
the variable "i" is out of scope on line 11. C++ allows for only one line of code to appear after a for loop or an if statement without needing braces. for anything else, you will need to add opening and closing braces to the control structure.
ah yes, the {} and semicolons. I always forget them. Thanks
I have another few related questions.
1) after i added the {} for blocks, i get the warning : test.cpp:9:29: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for the for header.
I added unsigned for int i in the for loop, and the warning is gone. So how come s was auto assigned as signed, and length() returns it back as unsigned?
2) if you can index strings in c++, what is the purpose of char?