【发布时间】:2011-08-03 18:41:50
【问题描述】:
我想我应该首先说我刚刚在我的电脑上安装了 linux(debian) 并且对在 linux 中做事的预知为零。这个问题可能是由于一些非常简单的事情造成的。
相关部分代码类似这样:
ifstream stockNames("names.txt");
while (!stockNames.eof())
{
string snline;
getline(stockNames,snline);
cout << snline << endl;
.
.
.
}
这应该打印文件“names.txt”的第一行。相反,它打印一个空行。当我尝试在另一个函数中使用 snline 作为输入时,我收到错误“分段错误”。我应该如何修改我的代码来做到这一点? linux中ifstream的用法有什么不同吗?因为在 Windows 中代码工作得很好
我已经写了下面的简单代码
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, const char *argv[])
{
string dos = "names.txt";
ifstream stockNames(dos.c_str() );
string snline;
while (getline(stockNames,snline))
{
cout << snline << " ";
}
return 0;
}
names.txt 的内容是
ABC
DEFG
HBO
cout
另一个更新:我又写了两个代码。
(1)
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, const char *argv[])
{
cout << "program has initiated" << endl;
ifstream stockNames("names.txt");
if( !stockNames )
cout << "unable to open" << endl;
string snline;
while (getline(stockNames,snline))
{
cout << snline << endl;
}
return 0;
}
结果如我所愿。首先是“节目已启动”,然后是不同行中的 ABC、DEFG、HBO。但是当我改变这部分时
cout << snline << endl;
作为
cout << snline << " hey" << endl;
然后 ABC DEFG HBO 没有出现,而是唯一的输出是“嘿”。
这太疯狂了,怎么会这样??
顺便说一句,我尝试使用 ddd 进行调试,当我检查变量 snline 时,ddd 打印以下行 (gdb) 打印 snline $2 = {静态 npos = 4294967295, _M_dataplus = {> = {<:new_allocator> = {}, }, _M_p = 0x804c1a4 "ABC\r"}}
新的迷你更新:当我将相关行更改为 "cout
【问题讨论】:
-
你确定names.txt在正确的目录吗?
-
"ABC\r":您的文件中有 windows 行终止符。用 dos2unix 打它。