【发布时间】:2021-01-26 07:03:02
【问题描述】:
我正在编写一个程序,在 C 中对文本文件执行简单的输入/输出操作。假设向用户显示几个选项,然后执行选定的操作并重新显示所述选项。我遇到的问题是我正在使用的 for 循环似乎循环了两次,因此显示的选项是两次。我不确定我做错了什么,任何帮助将不胜感激。
代码如下:
for (;;) {
printf("\nPlease choose from the fellowing options: \n\n");
printf("Press (S) to sreach for a word\n");
printf("Press (L) to display specified number of text lines to the screen\n");
printf("Press (A) to append new content to the file\n");
printf("Press (Q) to quit\n\n");
printf("Please enter option: ");
option = getchar();
if (option == 'S' || option == 's') {
//Search for a word in file.
printf("Test\n");
}
else if (option == 'L' || option == 'l') {
//Display number of line specified by user.
printf("Test\n");
}
else if (option == 'A' || option == 'a') {
//Append new content into file.
printf("Test\n");
}
else if (option == 'Q' || option == 'q') {
//Quit program.
exit(EXIT_SUCCESS);
}
else {
printf("Invalid input!\n");
}
}
这是输出:
请从奖学金选项中选择:
按 (S) 搜索单词 按 (L) 在屏幕上显示指定数量的文本行 按 (A) 将新内容附加到文件中 按 (Q) 退出
请输入选项:s 测试
请从奖学金选项中选择:
按 (S) 搜索单词 按 (L) 在屏幕上显示指定数量的文本行 按 (A) 将新内容附加到文件中 按 (Q) 退出
请输入选项:输入无效!
请从奖学金选项中选择:
按 (S) 搜索单词 按 (L) 在屏幕上显示指定数量的文本行 按 (A) 将新内容附加到文件中 按 (Q) 退出
请输入选项:
【问题讨论】:
-
printf("Invalid input '%c'!\n", option);在最后一个else你会弄明白的。
标签: c