gpt4 book ai didi

c++ - 如何从 C++ 中的输入读取文件路径以便打开 txt 文件?

转载 作者:行者123 更新时间:2023-11-28 07:15:28 26 4
gpt4 key购买 nike

我在 c:\\....\mydocuments 中有一个名为 myPoints.txt 的文件。它包含一些 x,y 点的列表(例如 3.4,5.6 )。我正在尝试使用 ifstream 打开它。一进入文件目录,我就收到运行时错误并且程序关闭。(例如...c:\mydocuments\myPoints.txt)

  1. 如何输入正确的文件目录?
  2. 有没有一种干净的方法可以将此代码放入以“ifstream ifs”作为参数的函数中??

这是我的文件打开代码:

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); 来代替,这样它会读取整行(即,您输入的所有内容,直到回车为止)。

关于c++ - 如何从 C++ 中的输入读取文件路径以便打开 txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com