Removing whitespace

Im trying to parse user input and remove unnecessary whitespace. This is my code:
1
2
3
4
5
6
7
8
9
10
11
void parseInput(std::string *in) {
	for (int i = 0; i < in->length(); i++) {
		if (in->at(i) >= 'a' && in->at(i) <= 'z') {
			in->at(i) -= ('a' - 'A');
		}
		if (in->at(i) == ' ' && in->at(i-1) == ' ') {
			in->erase(i, 1);
			--i;
		}
	}
}


The problem is that it removes everything after the first space is found. Anyone know what I'm doing wrong?
Last edited on
Try doing it using two strings. The original and one to store the result. Read the original and write to the result only if there are no consecutive spaces.

EDIT: There's a smarter way, using istringstream ;)

( http://cplusplus.com/reference/iostream/istringstream/ )
Last edited on
1
2
3
4
5
for( int i  = 0; i < in->length(); ++i){
  if(isspace(in[i])){
    in->erase(i,1);
  }
}
@RedX: I tried what you suggested and it doesn't seem to work :/

Anyway, the istringstream way is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

string SpaceTrim(const string & s);

int main()
{
    string input;

    cout << "enter input string:\n\n";
    getline(cin,input,'\n');

    cout <<  SpaceTrim(input) << endl;

    cout << "hit enter to quit..." << endl;
    cin.get();

    return 0;
}

string SpaceTrim(const string & s)
{
    istringstream iss(s);
    string result;
    string temp;

    //take advantage of the fact that
    //istream::operator>> skips whitespaces ;)
    while (iss>>temp)
    {
        result+=temp;
        
        //add exactly one whitespace
        //after each word
        result+=' ';
    }

    //remove last whitespace
    result.erase(result.end()-1);

    return result;
}
Last edited on
This one works
1
2
3
4
5
6

for( int i  = 0; i < in->length(); ++i){
  if(isspace(in->at(i))){
    *in = in->erase(i,1);
  }
}
@RedX
It does, but it doesn't do what OP wants. He only wants to remove unnecessary whitespaces.
E.g.: " hello world! " -> "hello world!"
Awesome, the istringstream works;) I'm just curious, because I used another implementation of the code in the original post, bit without the input being a pointer. It looks like this, and works fine:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string parseInput(string in, Bot *b) {
	char prevChar = ' ';
	for(int i = 0; i < in.length(); i++) {
		if (in[i] >= 'a' && in[i] <= 'z')
			in[i] -= ('a' - 'A');
		
		if (in[i] == '?')
			b->setQuestion(true);
			
		if (in[i] == ' ' && prevChar == ' ' || isPunc(in[i])) {
			in.erase(i, 1);
			i--;
		}
		
		prevChar = in[i];
	}
	return in;
}


I'm just wondering why this works, and not the other?

Thanks, all!
Topic archived. No new replies allowed.