c++ - Simple program with std::string is not working -
i learning std::string , want :
- input string
- every second letter make uppercase
output new string
#include "stdafx.h" #include <iostream> #include <string> using namespace std; int main() { string mystr; getline(cin,mystr); if (mystr.begin() != mystr.end()) { (auto = mystr.begin(); != mystr.end() ; += 2) *it = toupper(*it); } cout << mystr; system("pause"); return 0; }but after input getting error here:
it += 2 leads out of bounds, if loop ending condition it != mystr.end(). dereferencing
*it = toupper(*it); is undefined behavior.
it += 2 never give exact iterator value of mystr.end() have loops termination condition.
as comment:
so how can fix ?
just keep simple , understandable, e.g. using like
for (size_t = 0; < mystr.length() ; ++i) { if(i % 2) { // every second letter ... mystr[i] = toupper(mystr[i]); } }
Comments
Post a Comment