自从我使用C ++中的文件I / O(以及一般的C ++)以来已经有一段时间了,但我最近决定用它来为朋友制作一个小型控制台项目。 我的问题是我遇到了一些字符串数组和文件I / O的问题(我不确定是哪个引起了问题)。我的代码如下(ReadPSWDS是ifstream):
int i = 0;
string str[200];
ReadPSWDS.clear();
ReadPSWDS.open("myPasswords.DoNotOpen");
if(ReadPSWDS.is_open())
{
while(!ReadPSWDS.eof())
{
getline(ReadPSWDS, str[i]); //Store the line
if(str[i].length()<1 || str[i] == "")
{
//Ignore the line if it's nothing
}
else
{
i++; //Move onto the next 'cell' in the array
}
}
}
ReadPSWDS.close();
我的问题是,在测试时,字符串数组似乎是空的(并且在将所有这些行写入文件时,文件按预期为空)。 为什么字符串数组为空并且未填充文本文件的相应行?
此致
乔
答案 0 :(得分:6)
你写的循环显然是错误的:你之前正在测试eof()
失败,你没有在getline
之后测试失败。 C ++
I / O不具有预测性。 (我不能,因为你是否会eof()
取决于你试图阅读的内容。)正确的模式是:
while ( i < size(str) && getline( readSWDS, str[i] ) ) {
if ( !str[i].empty() ) {
++ i;
}
请注意,我已为i
添加了测试。如上所述,如果您的文件包含
超过200行,你遇到了麻烦。
'\n'
结尾,并且不为空,则为空
将在您的数组中出现两次。)当然,除非你的文件有
包含超过200行。
我可能会补充说,更典型的习惯用法是str
std::vector<std::string>
,并写下循环:
std::string line;
while ( std::getline( readSWDS, line ) ) {
if ( !line.empty() ) {
str.push_back(line);
}
}
这避免了必须定义固定的最大行数。