Originally Posted by
Salem
> while(true)
true isn't a C keyword.
Well, in fact everything Salem mentioned is a problem, as we are compiling C.
You just need to make a few changes to get Mr. Stroustrup's code to work:
Code:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
void quit(void) {
fprintf(stderr, "memory exhausted.\n");
exit(EXIT_FAILURE);
}
int main(void) {
size_t max = 20;
char *name = malloc(max);
char *morename;
int ch, i;
if (name == NULL) quit();
printf("Please enter your name: \n");
/* skipping whitespace */
do
ch = getchar();
while (ch != EOF && isspace(ch));
ungetc(ch, stdin);
for (i = 0; ; i++) /* add terminating zero */
{
ch = getchar();
if (ch == '\n' || ch == EOF)
{
name[i] = '\0';
break;
}
name[i] = ch;
if (i == max - 1) /* buffer full */
{
max = max + max;
morename = realloc(name, max);
if (morename == NULL)
{
free(name);
name = NULL;
quit();
}
name = morename;
}
}
printf("Hello %s.\n", name);
free(name);
return EXIT_SUCCESS;
}