我的 C 语言程序在开始时给出一个随机的 space,并在最后生成一个序列号
My C language program is giving a random space at the start and also generating one more serial number at the end
程序在“data.txt”文件的第一行生成了一个空白space,并且还生成了一个序列号。
#include<stdio.h>
#include<string.h>
int main(){
int limit;
int i = 0;
printf("How many approxmiate size of your list will be: \n");
scanf("%d", &limit);
char list[100][100];
FILE *store;
store = fopen("data.txt", "w");
while(i<=(limit - 1)){
printf("Enter task: \n");
gets(list[i]);
fprintf(store,"%s\n%d)",list[i], i+1);
i++;
}
fclose(store);
return 0;
}
这是因为 scanf("%d", &limit);
之后的换行符 ('\n'
) 保留在输入缓冲区中,要么将 scanf("%d", &limit);
更改为 scanf("%d ", &limit);
或更好,根本不要使用gets()
(使用gets()
是危险的:阅读原因here),而是使用fgets()
或scanf()
.
因此您的最终代码可能如下所示:
#include<stdio.h>
#include<string.h>
int main(){
int limit;
int i = 0;
printf("How many approxmiate size of your list will be: \n");
scanf("%d", &limit);
char list[100][100];
FILE *store;
store = fopen("data.txt", "w");
while(i<=(limit - 1)){
printf("Enter task: \n");
scanf(" %99[^\n]",list[i]);
fprintf(store,"%s\n%d)",list[i], i+1);
i++;
}
fclose(store);
return 0;
}
程序在“data.txt”文件的第一行生成了一个空白space,并且还生成了一个序列号。
#include<stdio.h>
#include<string.h>
int main(){
int limit;
int i = 0;
printf("How many approxmiate size of your list will be: \n");
scanf("%d", &limit);
char list[100][100];
FILE *store;
store = fopen("data.txt", "w");
while(i<=(limit - 1)){
printf("Enter task: \n");
gets(list[i]);
fprintf(store,"%s\n%d)",list[i], i+1);
i++;
}
fclose(store);
return 0;
}
这是因为 scanf("%d", &limit);
之后的换行符 ('\n'
) 保留在输入缓冲区中,要么将 scanf("%d", &limit);
更改为 scanf("%d ", &limit);
或更好,根本不要使用gets()
(使用gets()
是危险的:阅读原因here),而是使用fgets()
或scanf()
.
因此您的最终代码可能如下所示:
#include<stdio.h>
#include<string.h>
int main(){
int limit;
int i = 0;
printf("How many approxmiate size of your list will be: \n");
scanf("%d", &limit);
char list[100][100];
FILE *store;
store = fopen("data.txt", "w");
while(i<=(limit - 1)){
printf("Enter task: \n");
scanf(" %99[^\n]",list[i]);
fprintf(store,"%s\n%d)",list[i], i+1);
i++;
}
fclose(store);
return 0;
}