[英]Program that reads “n” lines from the user and writes it to a text file in C
I was asked to write a program that asks an integer from the user which represents that number of sentences that the user will write to the text file. 我被要求编写一个程序,向用户询问一个整数,该整数表示用户将要写入文本文件的句子数。 Then the user will write those sentences. 然后,用户将写下这些句子。 My problem with the my code below is that it only reads the first sentence that i;ve input and it will be written to the text file. 我下面的代码的问题是它只读取输入的第一句话,并将其写入文本文件。 what's wrong with it? 它出什么问题了? NOTE: the getline() won't work for some reason.keep on saying that "it was not declared on this scope". 注意:由于某些原因,getline()无效。请继续说“未在此作用域上声明”。 I'm using DEV-C btw. 我正在使用DEV-C btw。
main(){
int n;
char line[100];
FILE *in_file;
scanf("%d",&n);
in_file = fopen("lines.txt","w");
for(int i=0;i<n;i++){
gets(line);
fprintf(in_file,"%s",line);
}
fclose(in_file);
system("pause");
}
1) Instead of gets()
you should always use fgets()
. 1)应该始终使用fgets()
而不是gets()
fgets()
。
If you compile the code with gets()
you'll get the following warning on GCC: 如果使用gets()
编译代码,则会在GCC上收到以下警告:
/tmp/ccq8G5WV.o: In function `main': /tmp/ccq8G5WV.o:在“ main”函数中:
writelines.c:(.text+0x62): warning: the `gets' function is dangerous and should not be used. writelines.c :(。text + 0x62):警告:“ gets”功能很危险,不应使用。
2) After you enter number of lines to write in lines.txt
ie scanf("%d",&n);
2)输入行数以写入lines.txt
即scanf("%d",&n);
you need to remove \\n
from the input stream. 您需要从输入流中删除\\n
。
Try this example: 试试这个例子:
#include<stdio.h>
int main()
{
int n, i, c;
char line[100];
FILE *in_file;
scanf("%d",&n);
//Remove \n from input stream
while ( (c = getchar()) != '\n' && c != EOF );
in_file = fopen("lines.txt","w");
for(i=0; i<n; i++)
{
fgets(line, 100, stdin);
fprintf(in_file,"%s",line);
}
fclose(in_file);
return 0;
}
The above answer is very ok. 上面的答案很好。 scanf just read the characters before \\n and leave out the \\n in the stream buffer. scanf只是读取\\ n之前的字符,而将\\ n留在流缓冲区中。 You should remove it, otherwise it will count as one line. 您应该删除它,否则它将被视为一行。 Besides, fprintf should add \\n for very line because gets() also remove \\n from your input. 此外,fprintf应该在一行中添加\\ n,因为gets()还会从输入中删除\\ n。 If not, all lines will concantenate together and display one line. 如果不是,则所有行将合并在一起并显示一行。 I just combine the above answer and you original code. 我只是将以上答案与您的原始代码结合在一起。
#include <stdio.h>
int main(){
int n;
int i;
char c;
char line[100];
FILE *in_file;
scanf("%d",&n);
while ( (c = getchar()) != '\n' && c != EOF )
;
in_file = fopen("lines.txt","w");
for(i=0;i<n;i++){
gets(line);
fprintf(in_file,"%s\n",line);
}
fclose(in_file);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.