[英]Structures repeating entered data in C
我正在开发一个“C”编程语言类的项目。 我有一个问题,我一直无法找到补救措施。 问题在于我正在使用的结构。 它接受我输入的任何数据并重复6次。 我的代码是
对于结构:
struct authstruct
{
char userName[MAXCHAR];
char userPin[MAXCHAR];
};
正在接收输入的行
struct authstruct usr;
printf("Please enter your username\n");
scanf("%s",usr.userName);
while (fscanf(fident, "%s%s", auth.userName, auth.userPin) != EOF)
{
printf("%s", usr.userName);
};
请注意,我已将其设置为打印出用于测试目的的代码。 例如,如果您输入
test
它会踢出去
testtesttesttesttesttest
整个代码(忽略非相关函数,没有上述编辑)是:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* Defining of constants */
#define MAXCHAR 10
#define MAXATTEMPTS 3
#define SIZE 10
/* Prototypes */
int AuthFunc(void);
/* Prototype of structure for Authentication Function */
struct authstruct
{
char userName[MAXCHAR];
char userPin[MAXCHAR];
};
int main(VOID)
{
int login;
login = AuthFunc();
if (login == -1)
{
printf("namepass.txt could not be found\nPlease check for file and try again\n");
}
else if (login == 1)
{
printf("You have tried too many times to login\nPlease restart and try again\n");
}
else if (login == 0)
{
printf("Success!");
}
return 0;
}
/* This function authenticates the user */
int AuthFunc(void)
{
int i = 0;
FILE *fident;
fident=fopen("namepass.txt", "r");
if (fident==NULL)
{
return -2;
}
printf("Hello! Please follow my instructions\n");
struct authstruct auth;
for (i=0; i < MAXATTEMPTS; i++)
{
struct authstruct usr;
printf("Please enter your username\n");
scanf("%s",usr.userName);
while (fscanf(fident, "%s%s", auth.userName, auth.userPin) != EOF)
{
if ((strcmp(usr.userName, auth.userPin)) == 0)
{
printf ("Please enter your password.\n");
scanf ("%s",usr.userPin);
if ((strcmp(usr.userPin, auth.userPin)) == 0)
{
fclose(fident);
return 0;
}
}
}
printf("Incorrect username/password.\n");
}
fclose(fident);
return 1;
}
要运行此操作,您需要创建一个名为namepass.txt的新.txt文件,其中所选的用户名/密码排列在一行中,如下例所示
test 12345
test2 23456
我为长篇文章道歉,只是想尽可能地描述性。 这是在运行OSX 10.11.4的Mac上的Xcode 7.3中编译并运行的。 如果您的计算机上没有出现此问题,请告诉我,我将开始深入了解我的编译器设置。 谢谢
while (fscanf(fident, "%s%s", auth.userName, auth.userPin) != EOF)
看起来不对。 fscanf
返回一个int
,如果两个读数都通过则为2
。
将其修改为:
while (fscanf(fident, "%s%s", auth.userName, auth.userPin) == 2)
另外正如WhozCraig在评论中所提到的那样 ,您应该将文件倒回到开始或限制在AuthFunc
for
循环中的文件的打开和关闭。
来自man fscanf
:
这些函数返回成功匹配和分配的输入项的数量,这可以少于提供的数量,或者在早期匹配失败的情况下甚至为零。
如果在第一次成功转换或匹配失败发生之前达到输入结束,则返回值EOF。 如果发生读取错误,也会返回EOF,在这种情况下,将设置流的错误指示符(请参阅ferror(3)),并设置errno指示错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.