Apr 21, 2010 at 6:42pm UTC
I have a function that takes a string input and converts it to uppercase and removes excess spaces. This is the code:
string parseInput(string in) {
string out = in;
char prevChar = ' ';
for(int i = 0; i < in.length(); i++) {
if (out[i] >= 'a' && out[i] <= 'z')
out[i] -= ('a' - 'A');
if (out[i] == ' ' && prevChar == ' ')
out.erase(i, 1);
prevChar = out[i];
}
return out;
}
The function is called like this:
while(1) {
cout << ">";
cin >> input;
output = parseInput(input);
cout << output << endl;
}
The problem is that the erase() function seems to place a carriage return or something. The output of this is:
>test test
TEST
>TEST
>
What am I doing wrong here?
Apr 21, 2010 at 7:07pm UTC
The problem is that you're taking input with operator>>(), which takes space-separated input. Change it to std::getline(std::cin,input);
.
Apr 21, 2010 at 7:15pm UTC
Ok, that solved the carriage return problem.
However, after I switched to getline(), the output is like this:
http://pastebin.org/166181
This is kinda confusing to me. It changes almost all the characters to uppercase, but not all, and it removes only some of the spaces.
Last edited on Apr 21, 2010 at 7:16pm UTC
Apr 21, 2010 at 7:22pm UTC
after you erase a character, you'll need to decrement the counter.
1 2 3 4
if (out[i] == ' ' && prevChar == ' ' ) {
out.erase(i, 1);
i--;
}
And you'll need to make sure your for loop has the right test condition. 'out' is getting smaller, but you're testing the length of 'in'... that's going to cause some problems.
Last edited on Apr 21, 2010 at 7:26pm UTC