为什么这不起作用?我没有收到错误,我的程序崩溃了。
ifstream inStream;
inStream.open("Sample Credit Card numbers.txt");
string next[100];
for (int i = 0;!inStream.eof();i++)
{
next[i] = inStream.get();//fill in the array with numbers from file
}
我认为for循环的!inStream.eof()部分可能是问题,但我不太确定。
答案 0 :(得分:0)
试试这个:
for (int i = 0; ! inStream.eof() && i < 100; i++)
如果您可以调试程序,那么您可以进入for循环,如果它仍然崩溃,找出错误。
答案 1 :(得分:0)
循环直到eof()
几乎肯定不是你想要的。请参阅Why is iostream::eof inside a loop condition considered wrong?。
istream::get()
从流中提取一个字符并返回其值(强制转换为int
),但您将其放入std::string
数组中。这看起来很奇怪。
您还对100个元素的数组进行了硬编码,但没有检查以确保不会过度运行缓冲区。
相反,你应该喜欢这样的东西:
std::ifstream inStream("Sample Credit Card numbers.txt");
if (inStream)
{
std::string number;
std::vector<std::string> next;
while (std::getline(inStream, number))
{
next.push_back(number);
}
}
else
{
// Failed to open file. Report error.
}
答案 2 :(得分:0)
你的程序实际上对我来说很合适,文件中有一小组数字。但是,有两件事可能会导致您遇到问题: