Name: Anonymous 2012-11-03 14:43
Why it doesn't show me strings like " a"?
Why is the while loop in the trim function bugged (if I input 2 chars the next input length can't be less than 2)?
Why is the while loop in the trim function bugged (if I input 2 chars the next input length can't be less than 2)?
#include <stdio.h>
#define MAX 1001
int getLine(char s[], int length){ // returns 1 or 0
int i, qttWord = 0; //qttWord = counter of letters for s[]
int c; // c = getchar()
/*Reads the input and puts it into s[], then, verifies if the input is just \n,
* if so, returns 0(i), if not, puts '\0' at the end of the string.
*/
for (i = 0; i < length-1 && (c = getchar()) != EOF && c != '\n'; ++i){
s[i] = c;
++qttWord;
}
if (i == 0){
return 0;
} else if (c == '\n'){
++i;
s[i] = '\0';
}
/*Verifies if the string is just ' ' or '\t'
* if so, returns 0
*/
char flag = '\0';
for (i = 0; i < qttWord && flag != '1'; ++i){
if (s[i] == ' ' || s[i] == '\t'){
flag = '0';
} else{
flag = '1';
}
}
if (flag == '0')
return 0;
return qttWord;
}
void trim(char s[], int length){
char s2[MAX];
int i, qttWord = 0;
/*while (s[length] != '\0'){
++length;
}
printf("length:%d\n", length);*/
for (i = 0; i < length; ++i){
if (i < length-1){
if (s[i] == ' ' && s[i+1] != ' '){
s2[i] = s[i];
++qttWord;
printf("1:%d\n", s2[i]);// if true prints "1" and the character(' ')
}
}
if (s[i] != ' '){
s2[i] = s[i];
++qttWord;
printf("0:%d\n", s2[i]);//if true prints "0" and the character
}
}
s[0] = '\0';
s2[qttWord] = '\0';
for (i = 0; i < qttWord; ++i){
s[i] = s2[i];
}
s2[0] = '\0';
}
int main(){
char line[MAX];
int lgh = 0;
while ((lgh = getLine(line, MAX)) != 0){
trim(line, lgh);
printf("%s\n", line);
line[0] = '\0';
lgh = 0;
}
return 0;
}