从.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')
,它将在第一个密码处停止。当他到达第一个密码的末尾时,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
{...}
}
相关文章:
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 读取最后一行代码算法 - c++ 时出现问题
- 使用 seekg() 读取C++中的文件时出现问题
- 从矢量C++读取字符时出现问题
- 读取文件并将其存储在unordered_map中时出现问题
- 使用 minijson-reader 库读取 JSON 字符串时出现问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 读取制表符分隔的文件时出现问题 C++
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 我遇到使用 c++ 逐行读取输入文件的问题
- 关于读取有效 c++ 第 4 项(将非局部静态变量替换为局部静态变量)的问题
- 使用getline读取.csv文件时出现问题
- 在C++中读取 unicode 输入时出现问题
- 从文件中读取文本时出现编码问题
- 从标准输入读取多个类型时出现问题
- 使用管道从 STDIN 读取分叉进程时出现问题
- FSTREAM的问题读取确定,但不编写用户输入字符串
- 计数排序输出问题:读取访问冲突
- 问题读取预编译的着色器文件ID3DBlob