gpt4 book ai didi

c - 奇怪的扫描问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:42:50 24 4
gpt4 key购买 nike

我正在尝试完成一个将字符串与文本文件进行比较的家庭作业程序,因此用户基本上可以在文本文件中搜索文件中的搜索词(字符串)。我到了:)

但是今天我遇到了一个非常奇怪的问题。当它要求搜索术语时,我输入了文本,但它永远不会结束。我可以整天打字,但它仍然要求输入。我忽略了什么奇怪的问题?一双新鲜的眼睛可能会有所帮助:)

/*
ask the user for a word
convert user word to LOWER CASE
open output file
open input file
test to be sure input file is open
search for target word and keep count --> how??
print results to monitor
write results to file
close files
*/
#include<stdio.h>
#include<stdlib.h>

int main (void)
{
//declare
int i =0;
int count = 0;

/*************************************************************
working with arrays and strings
*************************************************************/
char mystring[50]; //what user puts in
char target[50]; //the word in the file we are looking for

printf("input your message ");
scanf("%s", mystring);
//printf("%s", mystring);


/*************************************************************
find file, write to it, output the string, end and close file
**************************************************************/

//define text file to use
FILE *cfile;
//name of file == file
cfile = fopen("./thanksgiving_proclamation.txt", "a");

//error handling if file does not exist
if(cfile == NULL) printf("Cannot open file");

/*************************************************************
parse through file and search for string
**************************************************************/
//convert string to lowercase
for(i = 0; i < /*strlen(mystring)*/ 500; i++)//convert to string length
{
if(target[i] >= 'A' && target[i] <='Z')
//convert char between a and z into lowercase
target[i] = target[i] + 32; //makes uppercase char
}

//compare our strings
do{
//scan through file
fscanf(cfile, "%s", mystring);

//convert string to lowercase
for(i = 0; i < /*strlen(mystring)*/ 300; i++)//convert to string length
{
if(mystring[i] >= 'A' && mystring[i] <='Z')
//convert char between a and z into lowercase
mystring[i] = mystring[i] + 32; //makes uppercase char
}
if(strcmp(mystring, target) == 0)
count++;
}while(!feof(cfile));

//while(strcmp(target,"quit")!=0)//end loop


//print to file
fprintf(cfile, "%s", mystring);

//close file
fclose(cfile);

//show user file has been written
printf("\nSuccess. File has been written\n");


printf("Press Enter to Continue...");
getchar();
return 0;
}

最佳答案

您以追加模式打开文件:

cfile = fopen("...", "a");

然后您尝试从中读取。

fscanf(cfile, "%s", mystring);

对于解决问题的第一次尝试,我会尝试打开文件进行读取,在循环内从中读取文件并关闭文件。然后再次打开它,这次是为了在其中添加 mystring(并 fclose 它)。

一旦成功,如果你愿意,试试看在“阅读和附加模式”下打开是否有效......

cfile = fopen("...", "a+");

关于c - 奇怪的扫描问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1820704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com