Hello guys.
I have a function, cleanSpace [which takes in a string such as
"this is\ta\ta a test". It cleans it up by removing new
lines/tabs and multiple/trailing and inbetween whitespace. I am
recieving a segmentation fault on one line when I apply it to a second
program [my second school assignment]. I was told from another source
that the problem is, is that the function is acting on constant string
literal. To fix this I was told to take the incoming string, copy it to
a buffer, work on the buffer and copy the buffer back to the original.
I tried but no sucess.
The seg fault is shown after the code snippet below.
int Account::cleanSpace(char c[])
{
int i=0,
j=0,
k=0,
m=0;
/* Ultimately this loop will scan for new lines and tabs and replace
them
with spaces. */
for(i=0; c[i]; i++)
{
if(c[i] == '\n' || c[i] == '\t')
c[i] = ' ';
}
/* For loop finds character starting point. */
for(i=0; c[i] == ' '; i++)
{
c[m] = c[i+1];
}
/* For loop moves all characters next to the first found character.
*/
for(i++; c[i]; i++)
{
c[++m] = c[i];
}
/* For loop removes trailing spaces. */
for(i = strlen(c) - 1; c[i] == ' '; i--)
{
c[i] = '\0';
}
/*For loop removes excess spaces. */
for(i = 0; c[i]; i++)
{
if(c[i] == ' ' && c[i+1] == ' ')
{
j = i;
while(c[j] == ' ')
{
j++;
}
for(k = i + 1; c[k]; k++, j++)
{
c[k] = c[j];
}
j=0;
}
}
return strlen(c);
}
Here is the function that calls it
int Account::changeCustomerInfo(char c[])
{
int result = 0;
char temp[251];
result = strlen(c) - 250;
cleanSpace(c); //Calls the cleanSpace function
if(strlen(c) <= 250){
strcpy(this->customer, c);
}
else{
for(int i = 0; i < 250; i++){
temp[i] = c[i];
}
strcpy(this->customer, temp);}
if(strlen(c) > 250){
return result;}
else return 0;
}
I recieve the seg fault on this code snippet below [which is found in
the cleanSpace function]
/* For loop moves all characters next to the first found character.
*/
for(i++; c[i]; i++)
{
c[++m] = c[i];
}
So by working with
int Account::cleanSpace(char c[]) function, how can I make it work not
on a string literal.
Thanks in advance. Appreciate any help whatsoever.