Hey guys I'm having a strange problem with my program and I'm not sure how to solve the problem.
I have a function which takes an array clears multiple white spaces to make a sentence so
"abc def ghi"
//becomes
"abc def ghi"
and it returns the length of the array. It is supposed to be 39 characters but my array keeps sending back 40 characters, if you could look into the program and help me out please.
#include<iostream>
using namespace std;
int cleanSpace(char s[]);
int main()
{
char d[] = "xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx";
int x = strlen(d);
strcpy(d, " widget;Acme \t \n Co.;gear induction\tdevice:\v \n ");
int result = cleanSpace(d);
if(result != 39)
{
printf("Failed test 7: cleanSpace should have returned 39, "
"your function returned %d\n\n", result);
exit(7);
}
cout << "\n" << result << "\n";
return 0;
}
int cleanSpace(char s[])
{
char temp[251];
int temp_index = 0;
int x = strlen(temp);
//create NULL array
for(int i = 0; i != x; i++){
temp[i] = '\0';
}
//remove certain special characters
for(int i = 0; s[i]; i++){
if(s[i] == '\t' || s[i] == '\n'){
s[i] = ' ';
}
}
//Remove leading spaces.
int i = 0;
while(s[i] == ' '){
i++;
}
//Remove middle spaces.
for(i; s[i]; i++){
if(s[i] != ' '){
temp[temp_index++] = s[i];
}
else{
if(s[i] == ' ' && s[i + 1] != ' '){
temp[temp_index++] = s[i];
}
}
}
temp[temp_index] = '\0';
cout << temp << "\n";
strcpy(s, temp);
return strlen(s);
}