#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
char * s_gets(char* st, int n);
enum spectrum { red, orange, yellow, green, blue, violet };
const char* colors[] = { "red","orange","yellow","green","blue","violet"};
#define LEN 30
int main(void)
{
char choice[LEN];
enum spectrum color;
bool color_is_found = false;
puts("enter a color (empty line to quit):");
while (s_gets(choice,LEN) != NULL && choice[0] != '\0')
{
//printf("");
for (color = red; color <= violet; color++)
{
printf("%s\n", colors[color]);
printf("%s\n", choice);
printf("%d\n", (strcmp(choice, colors[color])));
if (strcmp(choice, colors[color]) == 0)
//strcmp()函数比较两个字符串是否一样大
{
color_is_found = true;
break;
}
}
//printf("%d\n", color_is_found);
if (color_is_found)
{
switch (color)
{
case red:puts("roses are red.");
break;
case orange:puts("poppies are orange.");
break;
case yellow:puts("sunflowers are yellow.");
break;
case green:puts("grass is green.");
break;
case blue:puts("bluebells are blue.");
break;
case violet:puts("violets are violet.");
break;
}
}
else
{
printf("I don't know about the color %s.\n", choice);
}
color_is_found = false;
puts("next color,please (empty line to quit):");
}
puts("godbye!");
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
char* find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find= strchr(st, '\n');
if (find)
{
*find = '\n';
}
else
while (getchar() != '\n')
{
continue;
}
}
return ret_val;
}
c primer plus中14.15的例程程序,有错,不能显示正确程序效果。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
char * s_gets(char* st, int n);
enum spectrum { red, orange, yellow, green, blue, violet };
const char* colors[] = { "red","orange","yellow","green","blue","violet"};
#define LEN 30
int main(void)
{
char choice[LEN];
enum spectrum color;
bool color_is_found = false;
puts("enter a color (empty line to quit):");
while (s_gets(choice,LEN) != NULL && choice[0] != '\0')
{
//printf("");
for (color = red; color <= violet; color++)
{
printf("%s\n", colors[color]);
printf("%s\n", choice);
printf("%d\n", (strcmp(choice, colors[color])));
if (strcmp(choice, colors[color]) == 1)
//strcmp()函数比较两个字符串是否一样大
{
color_is_found = true;
break;
}
}
//printf("%d\n", color_is_found);
if (color_is_found)
{
switch (color)
{
case red:puts("roses are red.");
break;
case orange:puts("poppies are orange.");
break;
case yellow:puts("sunflowers are yellow.");
break;
case green:puts("grass is green.");
break;
case blue:puts("bluebells are blue.");
break;
case violet:puts("violets are violet.");
break;
}
}
else
{
printf("I don't know about the color %s.\n", choice);
}
color_is_found = false;
puts("next color,please (empty line to quit):");
}
puts("godbye!");
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
char* find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find= strchr(st, '\n');
if (find)
{
*find = '\n';
}
else
while (getchar() != '\n')
{
continue;
}
}
return ret_val;
}