从c语言的.txt文件中使用fgets扫描换行符



我有一个文本文件(fruits.txt),看起来像这样:

apple chloe
banana ben james
grape chloe james
kiwi ben chloe james
orange ben james
pear ben

我想将所有这些文本排序为

ben: banana kiwi pear
chloe: apple grape kiwi orange
james: banana grape kiwi orange

我最初的想法是使用fgets(),sscanf()fscanf(),但我遇到了相当多的问题,因为不是水果。txt中的所有行都有相同的单词量,这导致了一个固定的扫描格式

(such as fscanf("%s %s %s", name, fruit1, fruit2))

不可能,因此需要我从fruits.txt扫描一个换行符。然而,我想不出一种方法来编码它,因为它似乎扫描带有%s的字符串不包括换行符。

有人能帮我解决这个问题吗?如有任何帮助,不胜感激。

作为自己的练习,我实现了您正在寻找的内容。

您应该根据需要调整数组大小。它只是把输出输出到stdout,当然你可以把它改成你需要的文件。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PEOPLE    10
#define MAX_FRUIT     10
#define MAX_LINE_LEN  120
#define MAX_TOKEN_LEN 10

// Driver code
int main()
{
FILE* fp;
char line[MAX_LINE_LEN];
char person[MAX_PEOPLE][MAX_TOKEN_LEN] = {};
char fruit[MAX_FRUIT][MAX_TOKEN_LEN] = {};
int personFruit[MAX_PEOPLE][MAX_FRUIT] = {0};
int numFruit = 0;
int numPeople = 0;

// Open file in reading mode
fp = fopen("fruits.txt", "r");
if (NULL == fp) {
printf("file can't be opened n");
return 0;
}

// Process input file line by line
while (fgets(line, MAX_LINE_LEN, fp) != NULL) {
int nToken = 0, nFruitIndex = 0;
char* token = strtok(line, " ");
while (token != NULL) {
// Trim trailing line-feed if present
if (token[strlen(token) - 1] == 'n')
token[strlen(token) - 1] = '';
// Add first token to fruit array
if (nToken++ == 0) {
nFruitIndex = numFruit;
strcpy(fruit[numFruit++], token);
}
else {
// Process people tokens on line 
// Is this a new person or someone already encountered?
int nPersonIndex = 0, bFoundPerson = 0;
for (int i = 0; i < numPeople; i++) {
if (strcmp(token, person[i]) == 0) {
nPersonIndex = i;
bFoundPerson = 1;
break;
}
}
if (!bFoundPerson) {
nPersonIndex = numPeople;
strcpy(person[numPeople++], token);
}
personFruit[nPersonIndex][nFruitIndex]++;
}
// Get next token
token = strtok(NULL,  " ");
}
}
// Print output - list fruit each person has
for (int i = 0; i < numPeople; i++) {
printf("%s:", person[i]);
for (int j = 0; j < numFruit; j++)
if (personFruit[i][j] > 0)
printf(" %s", fruit[j]);
printf("n");
}
// Close file
fclose(fp);
return 0;
}

相关内容

  • 没有找到相关文章

最新更新