我想让我的代码询问用户,在void list((工作后,他/她是想使用void add(?
谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME_SIZE 128
#define MAX_LINE 2048
void list(){ // Printing the list.
char filename[100];
printf("n*** TODO List ***n ");
FILE *fptr ;
printf("nPlease enter the file name with its extension: ");
scanf("%s", filename);
fptr = fopen(filename, "r");
char ch[100]; // Character limit.
while(fgets(ch,sizeof(ch),fptr)){
printf("%s",ch);
}
}
void add(){ // Adding text to list.
char todo[150]; // Character limit.
char filename[100];
FILE *fptr ;
printf("n***TODO List - Add ToDo***n ");
printf("nPlease enter the file name with its extension:");
scanf("%s", filename);
fptr = fopen(filename, "a");
printf("nEnter todo:"); // Getting the text.
scanf("%s",todo);
fprintf(fptr,"n%s",todo); // Importing the text.
}
void delrow(){
printf("n***TODO List - Delete Rows***n ");
FILE *fileptr1, *fileptr2;
char filename[40];
// File name limit
char ch;
int delete_line, temp = 1;
printf("nPlease enter the file name with its extension: ");
scanf("%s", filename);
//open file in read mode
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
//rewind
rewind(fileptr1);
printf(" n Please enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
fileptr2 = fopen("temp", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == 'n')
temp++;
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
//rename the file temporary to original name
rename("temp", filename);
printf("n The contents of file after being modified are as follows:n");
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
}
int main(void) {
int choice=0;
list();
printf("nPlease state if you want to add todo or delete an existing todo (1:add 2:delete): ");
scanf("%d",&choice);
switch(choice){
case 1:
add();
case 2:
delrow();
default:
printf("nUnacceptable choice.");
}
return 0;
}
您必须添加break
语句,否则您的案例将通过进入下面的语句。
switch (choice) {
case 1:
add();
break;
case 2:
delrow();
break;
default:
printf("nUnacceptable choice.");
}
您的问题是的一个完美例子
为什么我应该始终启用编译器警告?
因为如果你在启用警告的情况下编译它,编译器会告诉你到底出了什么问题:
<source>: In function 'int main()':
<source>:116:16: warning: this statement may fall through [-Wimplicit-fallthrough=]
116 | add();
| ~~~^~
<source>:117:9: note: here
117 | case 2:
| ^~~~
<source>:118:19: warning: this statement may fall through [-Wimplicit-fallthrough=]
118 | delrow();
| ~~~~~~^~
<source>:119:9: note: here
119 | default:
| ^~~~~~~
"跌倒";意味着继续执行下一个案件。
Switch以贯穿机制而闻名。当发现特定情况时,执行附带标签中的语句,但执行将继续,直到到达[break;]语句或开关块的末尾。
在大多数情况下,逻辑设置将在单个事例块的末尾有break语句(尽管在许多情况下,使用fall-through算法(。您可以将[case1:]视为goto标签-程序跳到特定标签并从该点开始。
更重要的是,通常将单个事例中的语句放入{}块中是个好主意,尤其是当块中有局部变量声明时。