C语言字符串初级问题
还是C Primer Plus编程练习题里面的一道题,题目如下:
编写一个程序,读取输入,直到读入了10个字符串或遇到 EOF,由二者中最先被满足的那个终止读取过程,这个程序可以为用户提供一个有5个选项的菜单:输出初始字符串列表、按ASCII顺序输出字符串、按长度递增顺序输出字符串、按字符串中第一个单词的长度输出字符串和退出。菜单可以循环,直到用户输入退出请求。当然,程序要能整整完成菜单中的各种功能。
我的问题主要在这句话“读入了10个字符串或遇到 EOF”,以下是我未完成的代码:
#include <stdio.h>
#define N 10
#define MAX 81
void get_strings (char (*str)[MAX], int n);
int main (int argc, const char * argv[])
{
char nam[N][MAX];
int i = 0;
int c;
get_strings (nam, N);
puts("1.print the original list of strings");
puts("2.print the strings in ASCII collating sequence");
puts("3.print the strings in order of increasing lenth");
printf("4.print the strings in order of the length of the "
"first word int the string\n");
puts("5.quit");
while ((c = getchar()) != '5')
{
while (getchar() != '\n')
continue;
switch (c) {
case '1':
for (i = 0; i < N; i++)
puts(nam[i]);
break;
case '2':
case '3':
case '4':
default:
puts("Wrong input!");
break;
}
printf("enter your choice: ");
}// insert code here...
printf("Hello, World!\n");
return 0;
}
void get_strings (char (* str)[MAX], int n)
{
int i = 0;
while (i < N && (gets(str[i++]) != NULL));
}
我的问题主要是下面几个:
1. 当我输入5个字符串之后,按ctrl + D(unix系统模仿文件结尾的组合键),gets()函数返回NULL(空指针),这个时候,后面的getchar()函数无法继续读取数据,全部返回-1,导致程序无法进行下去,这是第一个问题。
2. 当向子函数传递字符串数组的时候,能否有更简洁的代码,我觉得我写的这种,内存利用率不高,而且代码量也多了点,但是我又不会其他的写法。当声明一个字符串数组的时候,可以通过初始化的方法创建长度参差不齐的字符串数组,作为参数传递的时候有没有简洁的写法?
[解决办法]