从.txt文件c++读取时出现问题

Issues with reading from a .txt file c++

本文关键字:问题 读取 txt 文件 c++      更新时间:2023-10-16

我在一个问题上寻求帮助。我必须从.txt文件中读取某些"密码",如"abE13#",并进行一些简单的错误检查,以确保它们符合某些要求。但目前,它正在打印密码(这是应该完成的),但它忽略了检查,并陷入了打印新行的循环中。我确信它必须与while(ch!='n')有关,但我不太确定需要什么来代替它进行检查。

ch = inFile.get();
while(!inFile.eof())
{
    while(ch != 'n')
    {
    cout << ch;
    if(isalpha(ch))
        {
            charReq++;
            if(isupper(ch))
                uppercaseReq++;
            else
                lowercaseReq++;
        }
    else if(isdigit(ch))
        {
            charReq++;
            digitReq++;
        }
    else if(isSpecial(ch))
        {
            charReq++;
            specialCharReq++;
        }
     if(uppercaseReq < 1)
           cout << "n missing uppercase" << endl;
     ch = inFile.get();
    }
}

它应该遵循这种格式,

Read a character from the password.txt file
while( there are characters in the file )
 {
 while( the character from the file is not a newline character )
{
Display the character from the file
Code a cascading decision statement to test for the various required characters
Increment a count of the number of characters in the password
Read another character from the password.txt file
}
Determine if the password was valid or not. If the password was invalid,
display the things that were wrong. If the password was valid, display that it
was valid.
Read another character from the file (this will get the character after the
newline character -- ie. the start of a new password or the end of file)
}
Display the total number of passwords, the number of valid passwords, and the
number of invalid passwords

由于这个while(inFile),它保持打印。这总是真的。将其更改为if语句,只是为了检查文件是否打开:

if ( inFile )

编辑:由于此while(ch != 'n'),它将在第一个密码处停止。当他到达第一个密码的末尾时,ch将为'\n',而失败并停止读取。更改为:

while( !inFile.eof() )
while( the character from the file is not a newline character )

您已经将这行伪代码转换为这行c++代码:

while (ch != 't')

't'是制表符,而不是换行符。这肯定会引起问题,为什么你永远不会结束,而只是打印出新行(真的是EOF,但你看不到)。

'n'是换行符。

试试看。

编辑:

此外,您唯一检查整个ifstream是否为false。我不知道什么时候会发生这种情况,但我建议检查EOF标志。你的代码应该变成这样的东西:

while( !inFile.eof() )
{
    while(ch != 'n' && !inFile.eof() )
    {
        // ...
    }
}

如果你不检查两次中缀,你可能会陷入一个无限循环。

while(infile.good())
{
    while (inFile.good() && ch != 'n')
    {
    ...
    }
    if (ch == 'n')
    {...}
    else
    {...}
}