Greetings.
I seek assistance with gaining an understanding of the following code. Below I submit a sample run, followed by the code itself.
Brief Synopsis: main() passes a char array reference to function getWord() which receives stdin from user. main() then attempts to print the string.
Error: strlen() is unable to ascertain the correct length of the string in main().
Code:
$ ./a.exe
hello
len = 7 //Incorrect. Proper length of 'hello' is 5
hello
P // junk characters
Code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 256
int getWord(char * newString, int size);
int main(){
int j;
int len;
char get[SIZE];
getWord(get, SIZE);
len = strlen(get);
printf("len = %d\n", len);
for(j=0; j<len; j++){
printf("%c", get[j]);
}
int getWord(char * newString, int size){
char a;
int i = 0;
while(i < size){
i++;
a = getchar();
if(a != '\n' && a != ' '){
*newString = a;
}
else if(a == '\n'){
*newString = '\n';
break;
}
else return 0;
newString += 1;
}
return 1;
}
Look forward to a prompt response.
Best regards,
wirefree101