C examples for String:char array
Read the first word from input into an array and discards the rest of the line
#include <stdio.h> #include <ctype.h> #include <stdbool.h> #define SIZE 20/*from ww w .ja va 2 s . c om*/ char * getword(char *target); int main(void){ char hello[SIZE] = "Hello, "; printf("What's your name?"); getword(hello + 7); puts(hello); return 0; } char * getword(char *target){ char ch; int i = 0; bool inword = false; while ((ch = getchar()) != EOF) { if (isspace(ch)){ if (inword) break; // word is over, exit while loop else{ continue; // skip leading whitespace } } if (!inword) inword = true; *(target + i) = ch; i++; } // discard rest of the line if any if (ch != '\n') while ((ch = getchar()) != '\n') continue; return target; }