我正在尝试制作这个小程序,需要帮助。
有.txt文件:
namas house
katinas cat
suo dog
skaicius number
我想找到以特定单词开头的一行,然后打印该行的第二个单词。
例如,用户输入单词 katinas
。程序查看文件,找到以 katinas
开头的行,最后打印。
我目前拥有的:
int main()
{
char word;
printf("Enter your word: ");
scanf("%s", &word);
FILE *fp;
fp = fopen("data.txt", "r+");
char buffer[256];
while (fgets(buffer, sizeof buffer, fp) != NULL && atoi(buffer) != word)
;
if (feof(fp))
{
printf(&buffer);
}
fclose(fp);
return 0;
}
谢谢。
最佳答案
正如其他地方指出的那样,代码中存在一些错误。这个答案会找到完整的单词,例如“suo”而不是“su”。
#include<stdio.h>
#include<string.h>
int main()
{
char word[256]; // adequate string space (not single char)
char buffer[256];
char *sptr;
FILE *fp;
int found = 0;
printf("Enter your word: ");
scanf("%s", word); // requires a string pointer (note no &)
fp = fopen("data.txt", "r"); // removed "+"
if (fp) {
while (fgets(buffer, sizeof buffer, fp) != NULL) {
sptr = strtok(buffer, " \t\r\n");
if (sptr && strcmp(sptr, word) == 0) {
sptr = strtok(NULL, " \t\r\n");
if (sptr) {
printf("%s\n", sptr);
found = 1;
break;
}
}
}
fclose(fp);
}
if (!found)
printf ("%s not found\n", word);
return 0;
}
关于c - 如何在文件中搜索以字符串开头的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31033451/