Hello... I'm trying to learn C after using a higher level language for several years. Honestly I feel like I am learning to walk again... Having a tough time!
In the code below I am attempting to extract the longest word from a string. I am still learning pointers so I very well may have messed that up.
It "seems" as though my new[] char array is holding the largest word when the program finishes, yet it doesn't print in the final print statement that's outside the for loop.
Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void append(char *s, char c) {
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
int main() {
int i, c = 0, l = 0;
char line[] = "Here is a phrase to test";
char new[] = "\0";
int length = strlen(line);
for (i = 0; i <= length; i++, c++) {
if (line[i] != ' ' && line[i] != '\0')
append(new, line[i]);
else {
if (c > l) {
l = c;
new[i] = '\0';
printf("longest so far: %s length: %d\n", new, strlen(new));
}
memset(&new[0], 0, sizeof(new));
c = 0;
}
printf("%s\n", new);
}
printf("Final output: %s", new);
return (0);
}
Here is the output from all of the print statements:
Code:
H
He
Her
Here
longest so far: Here length: 4
i
is
a
p
ph
phr
phra
phras
phrase
longest so far: phrase length: 6
t
to
t
te
tes
test
Final output:
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
Any tips would be appreciated. Thank you...
Here's the code without the print statements...