我在
c:\\....\mydocuments
中有一个名为 myPoints.txt 的文件。它包含一些 x,y 点的列表(例如 3.4,5.6 )。
我正在尝试使用 ifstream 打开它。
一旦我进入文件目录,我就会收到运行时错误并且程序将关闭。(例如...c:\mydocuments\myPoints.txt
)
这是我的文件打开代码:
int main()
{
cout << "Please enter the file name: ";
string name;
cin >> name;
ifstream ifs(name.c_str());
if (!ifs) error("can't open input file ", name);
vector < Point > points;
Point p;
while (ifs >> p) points.push_back(p);
// ....
}
不确定问题是否出在我的 ifstream 函数中,所以我将添加它以防万一:
ifstream& operator >>(ifstream& ifs, Point& p)
{
double x, y;
char comma;
ifs >> x >> comma >> y;
if (!ifs) return ifs;
if (comma != ',') {
ifs.clear(ios_base::failbit);
return ifs;
}
p = Point(x, y);
return ifs;
}
是的,您可以输入文件的完整路径。最主要的是您需要正确输入所有内容(例如,至少在大多数语言环境中,您需要在
My Documents
中留一个空格)。
另请注意,像
cin >> name;
这样的代码(其中 name
是 std::string
)只会读取第一个空白字符。您可能需要 std::getline(std::cin, name);
来代替,因此它将读取整行(即,您输入的所有内容,直到回车)。