我有一个程序可以打开一个文本文件并逐行读取。它还将每一行放入一个数组中。当我使用此函数并尝试使用 printf 语句中的每一行时,会添加新行字符。
我的代码:
char fileContents[MAX_LINES][MAX_LINE_LENGTH];
int lineCount = 0;
FILE *ifp = fopen("Tree-B.txt", "r");
if (ifp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
while (fgets(fileContents[lineCount++], MAX_LINE_LENGTH, ifp) != NULL);
fclose(ifp);
printf("Name: %s is now %s", fileContents[0], fileContents[1]);
输出如下:
Name: Tree Bacon
is now 30.21
printf 正在添加新行字符,我似乎无法发现为什么会发生这种情况。
从我的文本文件中读取的两行是:
Tree Bacon
30.21
最佳答案
我最喜欢的删除 fgets
读取的尾随 newline
的方法是使用 strcspn
while (fgets(fileContents[lineCount], MAX_LINE_LENGTH, ifp) != NULL) {
fileContents[lineCount] [ strcspn(fileContents[lineCount], "\r\n") ] = 0;
linecount++;
}
当然,您必须推迟增加数组索引。
关于C程序逐行读取文本文件时添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41883297/