我有一个任务要从文件中读取并将每个单词保存到链表中的节点中,然后在输出文件中再次打印文本,问题是我无法读取新行,当我打印到输出文件中时,所有文本变成一行,不像输入文件中那样,我该如何解决这个问题?
我尝试使用 fscanf 但它不读取新行
这是我的代码
struct node* LoadInput(){
FILE *fp;
fp = fopen("input.txt", "r");
if(fp == NULL){
printf("Error in opening the file!\n");
exit(3);
}
struct node* List = NULL;
List = MakeEmpty(List);
char Name[max_string];
while(fscanf(fp,"%s", Name) != EOF){
insertNode(List,Name);
}
fclose(fp);
return List;
}
使用
%s
扫描可以覆盖缓冲区。这定义了一个长度,为终止零分配一个额外的字符,并进行字符串化以限制扫描将处理的字符数。#include <stdio.h>
#include <stdlib.h>
#define LENGTH 50
// stringify to use in format string
#define FS(x) SFS(x)
#define SFS(x) #x
int main ( void) {
char word[LENGTH + 1] = ""; // allocate one for zero terminator
char newline[] = " ";
while ( 1 == scanf ( "%"FS(LENGTH)"s", word)) { // scan up to LENGTH non-whitespace characters
// this prints instead add word as another node
printf ( "-%s-", word);
scanf ( "%*[ \r\t\v]"); // scan and discard any whitespace except newline
if ( 1 == scanf ( "%1[\n]", newline)) { // scan for one character that must be newline
printf ( "%s", newline); // successful so print newline
// this breaks but instead add newline as another node
break;
}
// else scan for newline failed so continue while loop
}
return 0;
}