【问题标题】:How to read a file path from input in C++ so you can open a txt file?如何从 C++ 中的输入读取文件路径以便打开 txt 文件?
【发布时间】:2013-12-16 17:04:11
【问题描述】:

我在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;
}

【问题讨论】:

  • 不确定问题是否出在我的 ifstream 函数中,所以我会添加它以防万一:ifstream & operator>>(ifstream & ifs, Point & p) { double x, y;字符逗号; ifs>>x>>逗号>>y; if(!ifs) 返回 ifs; if(comma != ',') { ifs.clear(ios_base::failbit);返回如果; } p = 点(x,y);返回如果; }
  • 是的,您可以输入文件的完整路径。主要的是您需要正确输入所有内容(例如,至少在大多数语言环境中,您需要在 My Documents 中输入一个空格)。另请注意,cin &gt;&gt; name; 最多只能读取第一个空白字符。你可能想要std::getline(cin, name);,所以它会读一整行。
  • 不要在 cmets 中发布代码,将其编辑到问题中。
  • 尝试使用正斜杠“/”,而不是反斜杠“\”。适用于 *nix 和 Windows 平台。
  • @JerryCoffin:您的评论就是一个答案。我认为你应该做一个。

标签: c++ c++11 file-io iostream istream


【解决方案1】:

是的,您可以输入文件的完整路径。主要的是您需要正确输入所有内容(例如,至少在大多数语言环境中,您需要在My Documents 中留一个空格)。

另请注意,cin &gt;&gt; name;(其中namestd::string)之类的代码只能读取到第一个空白字符。你可能想要std::getline(std::cin, name);,所以它会读取一整行(即,你输入的所有内容,直到回车)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多