【发布时间】:2013-02-09 22:16:22
【问题描述】:
我在为作业执行的某些代码方面遇到问题。当我去编译文件时,它有时可以工作,有时不能。该程序的基本思想是从文件中读取每一行文本并将其存储到一个数组中(数组的大小应该是100,应该有100行文本)。每个文本字符串(每一行)都应该存储在它自己的数组地址中。一旦存储了所有行,程序将从数组中提取每一行,并注意它来自哪个行号。当用 Code::Blocks 编译它时,它运行没有问题,但是,当我用 cygwin 编译它时,我去运行它并收到一条错误消息,上面写着 “在抛出 'std::bad_cast' 的实例后调用终止 什么():std::bad_cast 中止(核心转储)”
如果你们能给我任何帮助,我们将不胜感激!
这是我目前得到的代码:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string aFile[100];
ifstream nFile("TMA1Question4 Text.txt");
string nText;
if (nFile)
{
for (int nLineCounter=1; nLineCounter <=100; getline(nFile, nText))
{
aFile [nLineCounter] = nText;
nLineCounter++;
}
}
for (int nLineReader=1; nLineReader<=100; nLineReader++)
{
cout << "Line" << nLineReader << ": " << aFile[nLineReader] << endl;
}
return 0;
}
【问题讨论】:
-
如果文件无法访问会怎样?
-
你的 for 循环应该从 0 开始到
< 100 -
除了答案之外,当您
cout执行nLineReader + 1时,这将为您提供正确的行号。
标签: c++