为什么当 ifstream 创建从键盘读取字符串的文件时出现错误

Why do I get error when ifstream is creating file with string read from keyboard?

本文关键字:文件 错误 字符串 读取 ifstream 创建 键盘 为什么      更新时间:2023-10-16

我正在做Bjarne Stroustrup的书《Programming Principles and Practice Using C++》中的练习。我正在讨论第10章的第一个练习,它说编写一个程序,在空格分隔的整数文件中生成所有数字的总和。我下面的代码基于第 10.5 章练习 2 中使用的代码。创建ifstream对象时出现错误。这是我尝试运行的代码:

#include "../../std_lib_facilities.h"
int main(int argc, const char * argv[]) {
    // insert code here...
    cout << "Plese enter the input file name: " << endl;
    string iname;
    cin >> iname;
    ifstream ist {iname};
    if (!ist) error("Can't open input file ",iname);
    vector<int> numbers;
    int sum;
    int n;
    while(ist>>n) {
        numbers.push_back(n);
    }
    for (int i=0; i<numbers.size(); ++i) {
        sum += numbers[i];
    }
    cout << sum << endl;
    return 0;
}

我输入的任何输入都出错。我尝试了myin,myin.txt或任何其他名称。error("Can't open input file ",iname);来自作者创建的库。

我知道该文件确实存在于与main相同的目录中.cpp并且使用纯文本格式从Mac使用TextEdit创建。

[...]

在与 main 相同的目录中.cpp [...]

将输入文件相对于源文件放置在哪里并不重要。运行程序时,该文件应位于环境的当前工作目录中。

在传递论证时一定有一些混乱。您应该尝试传递输入文件的绝对路径。

下面是您修改的应用程序。这将创建一个测试文件并使用它,而不是询问案例 1 的文件名。对于情况 2,它使用不存在的文件。(如果存在,请删除(

#include <cstdio>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
template <typename T> void error(const T &t) { cout << t; }
template <typename T, typename... Args> void error(const T &t, Args... args) {
  cout << t << " ";
  error(args...);
  cout << "n";
}
int main(int argc, const char *argv[]) {
  // insert code here...
  // cout << "Plese enter the input file name: " << endl;
  string iname = "a.txt";
  ofstream ofs{iname};
  ofs << 1 << " " << 2 << " " << 3 << " " << 4;
  ofs.close();
  //  cin >> iname;
  // part 1
  {
    cout << "Case1: Reading file a.txt which is just createdn";
    ifstream ist{iname};
    if (!ist)
      error("Can't open input file ", iname);
    if (ist.is_open()) {
      vector<int> numbers;
      int sum = 0;
      int n = 0;
      while (ist >> n) {
        numbers.push_back(n);
      }
      for (int i = 0; i < numbers.size(); ++i) {
        sum += numbers[i];
      }
      cout << sum << endl;
      ist.close();
    } else {
      error("can't open file to read", iname);
    }
  }
  // part 2
  {
    cout << "Case2:reading file which is not presentn";
    iname = "b.txt";
    std::remove(iname.c_str()); // delete if present
    ifstream ist{iname};
    if (!ist)
      error("Can't open input file ", iname);
    if (ist.is_open()) {
      vector<int> numbers;
      int sum = 0;
      int n = 0;
      while (ist >> n) {
        numbers.push_back(n);
      }
      for (int i = 0; i < numbers.size(); ++i) {
        sum += numbers[i];
      }
      cout << sum << endl;
      ist.close();
    } else {
      error("can't open file to read", iname);
    }
  }
  return 0;
}

注意:std::ifstream的构造始终创建对象。您需要像以前一样或is_open()方法对其对象。