我有一個文本檔案 (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
在 C 程式中。
本來想用fgets(), sscanf()orfscanf()的,但是遇到了很多問題,因為 fruits.txt 中并非所有行的字數都一樣,導致掃描格式固定
(such as fscanf("%s %s %s", name, fruit1, fruit2))
不可能,因此需要我從 fruits.txt 中掃描一個換行符。但是,我想不出一種編碼方法,因為它似乎在使用 %s 掃描字串時不包含換行符。
有人可以幫我解決這個問題嗎?任何幫助將不勝感激。
uj5u.com熱心網友回復:
作為我自己的練習,我實作了你正在尋找的東西。
您應該根據需要調整陣列大小。它只是將輸出列印到,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] = '\0';
// 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531138.html
標籤:C细绳扫描
上一篇:EJS檔案可以接收物件嗎?
