如何将文件读取为字符串数组;奇怪的错误
How to read a file into an array of strings; strange error
为什么不起作用?我没有收到错误,我的程序只是崩溃了。
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循环,如果它仍然崩溃,你可以找出问题所在。
您的程序实际上对我来说运行得很好,文件中只有一组很小的数字。然而,有两件事可能会给你带来问题:
- 你不会检查文件是否成功打开,如果不成功,就会崩溃
- 你没有检查你的数组中是否有足够的字符串,如果你的文件中的数字超过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.
}
相关文章:
- "错误:数组下标的无效类型'float [10001][float]'是什么意思?
- 错误:数组下标的类型"const bool[int]"无效
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 使用GCC 4.8构建错误:数组用作初始化器
- 如何修复问题中的"teminated due to timeout"错误 数组操作 |黑客兰克?
- | 9 |错误:非静态数据成员'matrix :: row'| 9 |错误:数组绑定不是在']']'令牌|之前的整数常数
- 错误:数组的总大小不得超过0x7fffffff字节
- 错误:无法将参数“1”的“double*”转换为“double”,错误:数组下标的类型“double[double]”无
- 返回并强制转换数组指针(错误:数组下标的类型..无效)
- 返回c++中的字符错误数组
- VC++错误:数组实例化的大小来自模板化的静态常量
- c++mex错误:数组下标的类型“double[mwSize]”无效
- 错误数组用作初始值设定项,我不知道错误
- 编译错误 - 数组下标'char[int]'的类型无效
- 向量在我的类中.错误:数组new [-fpermissive]中的圆括号初始化项
- 错误:数组下标的类型无效
- 错误:数组new中的size必须是整型[-fpermissive]
- 错误:数组下标的“Pixel*[__complex__ int]”类型无效
- c++错误数组显示
- C++:错误:数组下标的类型“size_t{aka long unsigned int}[size_t{aka long