Function to remove spaces

Write a function that takes a string as an input and gets rid of the extra spaces in the beginning of a word. For example if the string is “ university” then RemoveLeadingSpaces function should make it “university”

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
 #include <iostream>

using namespace std;

void RS (char arr[] , int size) // RS means remove spaces
{
    for (int x=0; arr[x]!='\0'; x++)
    {
        if (arr[x]==' ')
        {
            arr[x]=arr[x+1];
        }
            x--;

    }
        for (int j=0; arr[j]!='\0'; j++)
        {
        cout << arr[j];
        }
        cout<<endl;
}


int main()

{
    char name [100];
    cout <<"Enter a sentence"<<endl;
    cin.getline(name,100);

    RS (name , 100);
}




Can any one please tell me the error in it
1
2
3
4
5
6
7
8
9
for (int x=0; arr[x]!='\0'; x++)
{
    if (arr[x]==' ')
    {
        arr[x]=arr[x+1];
    }
        x--;

}


In this loop, you're telling x to increment, then at the end of the loop you're telling x to decrement. x doesn't change.
This is infinite loop:
1
2
3
4
5
6
7
8
9
for (int x=0; arr[x]!='\0'; x++)// <------+ This plus...
{                                   //    |
	if (arr[x]==' ')            //    |
	{                           //    |
		arr[x]=arr[x+1];    //    |
	}                           //    |
	x--; // <-------------------------+
	     // ...negates this minus
}
Last edited on
Thank You guys :)

I got it

here is the perfect code

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
#include <iostream>

using namespace std;

void RS (char arr[] , int size)
{
    for (int x=0; arr[x]!='\0'; x++)
    {
        if (arr[x]==' ')
        {
            for (int k =x; arr[k]!='\0'; k++)
            arr[k]=arr[k+1];
            x--;
        }

    }
        for (int j=0; arr[j]!='\0'; j++)
        {
        cout << arr[j];
        }
        cout<<endl;
}


int main()

{
    char name [100];
    cout <<"Enter a sentence"<<endl;
    cin.getline(name,100);

    RS (name , 100);
}


Topic archived. No new replies allowed.