【发布时间】:2019-09-22 03:38:48
【问题描述】:
我想比较字符串用户输入和文本文件中的字符串。
我正在比较 uname 的值和存储的当前值。它进入 while 循环,但是当它们匹配时,它不会进入 if 块,如果 storage 和 uname 具有相同的值,则该块应该进行测试。
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");
}
}
}
【问题讨论】:
-
我怀疑您从文件中读取的行尾可能有换行符!
-
写一些类似 perl 的 chomp 的东西来从使用 fgets 读取的行尾删除 '\n' 或 '\r\n'。您还可以使用 fgets(storage,sizeof(storage),stdin) 后跟 chomp(storage) 和 strncpy(uname,storage,sizeof(uname)-10),而不是 scanf...
-
char uname[20];,见C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3),uname已经是一个指针,所以scanf("%s",&uname);中不需要&。
标签: c