示例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //C99特性
#include <string.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
/* C允许同名,C++不允许. 例如下面代码:*/
struct rect { double x; double y; };
int rect;
int main(int argc, char* argv[])
{
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')
{
for (color = red; color <= violet; color++)
{
if (strcmp(choice, colors[color]) == 0)
{
color_is_found = true;
break;
}
}
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 are green.");
break;
case blue:
puts("Bluebells are blue.");
break;
case violet:
puts("Violets are violet.");
break;
default:
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("Goodbye!");
system("pause");
return 0;
}
// 自己实现读取函数
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val) //即,ret_val != NULL
{
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
运行测试