繁体   English   中英

从 .txt 文件 C++ 读取的问题

[英]Issues with reading from a .txt file c++

我在某个问题上寻求帮助。 我必须从 .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')在第一个密码处停止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 是否为假。 我不太清楚什么时候会发生,但我建议检查 EOF 标志。 你的代码应该变成这样的:

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

如果您不检查 infile 两次,您可能会陷入无限循环。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM