比较C中文本文件中的字符串
我想比较字符串用户输入和文本文件中的字符串 我正在比较uname的值和存储的当前值。它进入while循环,但当它们匹配时,它不会进入if块,如果存储和uname具有相同的值,则if块应该进行测试比较C中文本文件中的字符串,c,C,我想比较字符串用户输入和文本文件中的字符串 我正在比较uname的值和存储的当前值。它进入while循环,但当它们匹配时,它不会进入if块,如果存储和uname具有相同的值,则if块应该进行测试 void compare() { char uname[20]; FILE *list = fopen("list.txt","a"); if(list == NULL) { printf("Textfile doesn't have any content\n")
void compare()
{
char uname[20];
FILE *list = fopen("list.txt","a");
if(list == NULL)
{
printf("Textfile doesn't have any content\n");
}
printf("Enter username: ");
scanf("%s",&uname);
fprintf(list,"%s\n",uname);
fclose(list);
list = fopen("listahan.txt","r");
char storage[50]; //storage of the string that I will get from the textfile
if(list != NULL) //check if list have content
{
while((fgets(storage,sizeof(storage),list) != NULL)) //if list have content, get it line by line and compare it to the uname.
{
printf("storage:%s\n",storage); // for debug, checks the current value of storage
printf("uname:%s\n",uname); //for debug, checks the value of uname
if(storage == uname) //this if block is being ignored, even when the storage and uname match, the block does not execute.
{
printf("Login Success!\n");
}
}
}
输入字符数组时,无需指定&uname 将其更正为:
scanf("%s",uname);
其余更正:
if(list != NULL) //check if list have content
{
while(fgets(storage,sizeof(storage),list) != NULL) //if list have content, get it line by line and compare it to the uname.
{
if (*storage == '\n')
continue;
sscanf(storage, "%[^\n]", storage);
printf("storage:%s\n",storage); // for debug, checks the current value of storage
printf("uname:%s\n",uname); //for debug, checks the value of uname
if(!strcmp(storage, uname)) //this if block is being ignored, even when the storage and uname match, the block does not execute.
{
printf("Login Success!\n");
}
}
}
此外,您可以简单地使用fscanf而不是fgets,但这是一个非常糟糕的主意,请阅读中的第一个答案
因此,首先您需要将值存储在存储器中
如合同所述:
fgets从流中最多读取一个小于大小的字符,并将它们存储到s指向的缓冲区中。EOF或换行符后,读取停止。如果新行被读取,它将被存储到缓冲区中。终止的空字节aq\0aq存储在缓冲区中最后一个字符之后
简而言之,如果遇到换行符,读取将停止,但它也将被存储
所以用户名!=用户名\n。这就是为什么我们再次将该字符串压缩为同一个字符串,直到\n为止
此外,要比较字符数组,还需要使用strcmp如果您正在比较char*您正在比较存储阵列的地址和uname阵列的地址,则该选项将起作用。它始终为false。您必须使用strcmpstorage,uname in condition来比较两个数组的字符串。我怀疑您从文件中读取的行末尾可能有换行符!编写类似于perl的chomp的内容,使用fgets从行尾读取中剥离“\n”或“\r\n”。您还可以使用fgetsstorage、sizeofstorage、stdin,后跟chompstorage和strncpuname、storage、sizeofuname-10,而不是scanf…char uname[20];,请参阅,uname已经是指针,因此在scanf%s中没有&required,&uname;。您也可以简单地使用存储器[strcspn storage,\n]=0;修剪'\n';。如果您使用的是sscanf,这很好,您确实需要检查退货,例如,如果sscanf..=1{/*handle error*/}因为fgets会很高兴地读取一个只存储“\n”的空行,如果您不检查sscanf返回可能会让您感到惊讶。@DavidC.Rankin,是否有必要,因为如果存储是空的,strcmp根本不会匹配并继续下一行。还有其他原因吗?谢谢。你是对的,不会有错误,你只会输出和比较一个空字符串,这可能是不可取的。您也可以只检查*storage='\n'是否继续;您在sscanf@DavidC.Rankin之前致电fgets后,我立即做出了更改,谢谢。