【发布时间】:2014-05-02 06:31:57
【问题描述】:
这是相关代码。整个项目编译没有问题。
list<Line> loadText(const string &textFile)
{
ifstream txt;
string temp;
char ch;
list<Line> fullText;
unsigned length;
txt.open(textFile.c_str());
if (!txt)
{
cout << "Can't open " << txtFile << " \n";
exit(1);
}
// process file line by line
txt.seekg (0, ios::end);
length = txt.tellg();
txt.seekg (0, ios::beg);
cout << length;
for(int j = 0; j < length; j++)
{
cout << j;
txt.get(ch);
temp += ch;
cout << ch;
if (ch == '\n')
{
cout << temp;
Line line(temp);
row.printLine();
fullText.push_back(row);
cout<< "line done \n";
}
}
所以这个函数是用来获取一个文本文件,并创建一个行列表(一个存储字符列表的自定义类)。所有的“cout”都用于调试目的。
如果我输入这样的文本文件:
Line 1
Line 2
Line 3
Line 4
我得到这样的输出:
loading maze...
30 0L1i2n3e4 516
Line 1
Line 1
line done
destroyed
请注意,destroyed 只是在调用 Lines 析构函数时给出的输出。
所以很明显它在第一次迭代之后就出现了问题,但是经过几个小时的尝试解决这个问题,我还没有弄清楚。
【问题讨论】:
-
贴出的功能不完整。它缺少
return语句以及结束}。 -
使用
getline逐行读取。 -
读完每一行后,清除
temp变量。 -
另外,在 Windows 上,在换行符之前有一个回车符,这意味着“插入指针”移动到控制台中的行首,这可能会导致有趣的打印输出中的东西。最好使用
getline(),然后用std::endl连接字符串,而不是用'\n'结束它们。
标签: c++