I read a book about c++ and am having trouble digesting this function:
void eatspaces(char* str)
{
int i = 0; // 'Copy to' index to string
int j = 0; // 'Copy from' index to string
while((*(str + i) = *(str + j++)) != '\0') // Loop while character
// copied is not \0
if(*(str + i) != ' ') // Increment i as long as
i++; // character is not a space
return;
}
it's suppose to delete spaces.
I tried to see if I could understand it by building a program, but gets an error after inputting something:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const int MAX = 80;
char buffer[MAX]={0};
int i = 0;
int j = 0;
char* str;
cin.getline(buffer, sizeof buffer);
while((*(str + i) = *(str + j++)) != '\0') // Loop while character
{ // copied is not \0
if(*(str + i) != ' ') // Increment i as long as
i++; // character is not a space
cout << j
<< endl;
}
cout << buffer;
return 0;
}
Can anyone please explain how it works and why I'm having an error?
The code iterates over each character copying them backwards and just skipping spaces. Not really nice code imo.
However, yours crashes because you've assigned a variable char *str; but not assigned anything to it. Since it's not in a known state, it's going to cause undefined behaviour in your application when you try to remove spaces from it. Assign something to it before you try to remove spaces from it.