How to input for x = ( 1 to total length of a string ) in c++?
- llafferLv 73 weeks ago
in java, I would use:
for (int x = 1; x <= str.length(); x++)
It has been about 25 years since I've looked at C++, so not sure what string methods exist there, but there should be something similar.
- husoskiLv 73 weeks ago
If that string really is a C++ string, using the <string> header, then the for loop you seem to be asking for is:
std::cin >> s;
for (unsigned x = 1; x <= s.size(); ++x)
// do something with x here
Using unsigned instead of int cuts out warnings about signed-vs-unsigned comparisons. (For obscure, edge-case reasons, the string length is returned as an unsigned type.)
Are you sure you want to loop on from 1 to n? Remember that string and array index values start at 0 for the first position in C++, as in Java an many other languages. If you are going to look at the x'th character of the string s in that loop, be sure to use s[x-1] instead of s[x].