我正在嘗試將單詞從一個檔案復制到另一個檔案,但單詞必須以給定字母開頭。它正在作業,但不會復制匹配的每個單詞。
#include <stdio.h>
int main() {
FILE *f = fopen("words.txt", "r");
FILE *f2 = fopen("words_copy.txt", "a ");
char usr;
printf("enter letter: ");
scanf("%c", &usr);
char buffer[255];
char ch, ch2;
while ((ch = fgetc(f)) != EOF) {
ch2 = fgetc(f);
if (ch2 == usr && ch == '\n') {
fputc(ch2, f2);
fgets(buffer, sizeof(buffer), f);
fputs(buffer, f2);
}
}
return 0;
}
Words.txt包含:
adorable aesthetic alluring angelic appealing arresting attractive
blooming charismatic charming cherubic chocolate-box classy contagious
cute dazzling debonair decorative delectable delicate distinguished
enchanting enticing eye-catching glamorous glossy good-looking
gorgeous infectious lovely lush magnetic magnificent majestic melting
mesmerizing noble picturesque poetic prepossessing shimmering striking
stunning winsome
每個單詞都在下一行,當我運行程式并給出字母m words_copy.txt僅包含:
magnificent melting
如何修復以匹配字母復制每個單詞?
uj5u.com熱心網友回復:
回圈中的測驗不正確:您檢查換行符后的第一個字母,如果匹配則輸出該行。有了這個邏輯:
- 您無法匹配檔案中的第一個單詞
- 你只匹配以
usr - 并且匹配后的單詞被忽略
此外,您ch應該ch2定義型別int以可靠地匹配EOF,您應該測驗fopen失敗并在使用后關閉檔案。
您應該使用更簡單的方法:
- 讀一個字
- 測驗它是否包含字母
- 如果匹配,則輸出單詞
這是修改后的版本:
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char usr;
char buffer[256];
int ch = 0;
size_t pos;
FILE *f = fopen("words.txt", "r");
if (f == NULL) {
fprintf(stderr, "cannot open words.txt: %s\n", strerror(errno));
return 1;
}
FILE *f2 = fopen("words_copy.txt", "a ");
if (f2 == NULL) {
fprintf(stderr, "cannot open words_copy.txt: %s\n", strerror(errno));
fclose(f);
return 1;
}
printf("enter letter: ");
if (scanf(" %c", &usr) != 1) {
fprintf(stderr, "missing input\n");
fclose(f);
fclose(f2);
return 1;
}
while (ch != EOF) {
pos = 0;
/* read a word, stop at whitespace and end of file */
while ((ch = fgetc(f)) != EOF && !isspace(ch)) {
if (pos 1 < sizeof(buffer))
buffer[pos ] = (char)ch;
}
buffer[pos] = '\0';
/* test for a match */
if (strchr(buffer, usr)) {
/* output matching word */
fprintf(f2, "%s\n", buffer);
}
}
fclose(f);
fclose(f2);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487156.html
上一篇:鏈表中的指標
