如何将文件读取为字符串数组;奇怪的错误

How to read a file into an array of strings; strange error

本文关键字:错误 数组 字符串 文件 读取      更新时间:2023-10-16

为什么不起作用?我没有收到错误,我的程序只是崩溃了。

    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.of()部分可能有问题,但我不太确定。

试试这个:

for (int i = 0; ! inStream.eof() && i < 100; i++)

如果你可以调试你的程序,那么你可以进入for循环,如果它仍然崩溃,你可以找出问题所在。

您的程序实际上对我来说运行得很好,文件中只有一组很小的数字。然而,有两件事可能会给你带来问题:

  1. 你不会检查文件是否成功打开,如果不成功,就会崩溃
  2. 你没有检查你的数组中是否有足够的字符串,如果你的文件中的数字超过100怎么办?这也会导致崩溃

循环到eof()几乎肯定不是你想要做的。请参阅为什么循环条件中的iostream::eof被认为是错误的。

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.
}