简体   繁体   English

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

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

I am doing exercises from Bjarne Stroustrup's book, Programming Principles and Practice Using C++ . 我正在Bjarne Stroustrup的书《使用C ++编程原理和实践》中进行练习 I am on the first exercise in Chapter 10 , where it says to write a program that produces the sum of all the numbers in a file of whitespace-separated integers. 我正在第10章中进行一个练习,该练习说要编写一个程序,该程序在以空格分隔的整数文件中生成所有数字的和。 I based my code below on what's used for Exercise 2 of Chapter 10.5 . 我下面的代码基于第10.5章的练习2中使用的代码。 I get an error when the ifstream object is created. 创建ifstream对象时出现错误。 Here is the code I am trying to run: 这是我尝试运行的代码:

#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;
}

Any input I enter is getting error. 我输入的任何输入都出错。 I tried myin, myin.txt or any other name. 我尝试了myin,myin.txt或其他任何名称。 The error("Can't open input file ",iname); error("Can't open input file ",iname); is from the library created by the author. 来自作者创建的库。

I know the file does exist in the same directory with main.cpp and created with TextEdit from Mac using the format for plain text. 我知道该文件确实与main.cpp存在于同一目录中,并使用纯文本格式从Mac使用TextEdit创建。

[...] in the same directory with main.cpp [...] [...]与main.cpp在同一目录中[...]

It does not really matter where you put the input file relative to the source file. 相对于源文件放置输入文件的位置并不重要。 The file should be in the environment's current working directory when you run the program. 运行程序时,该文件应位于环境的当前工作目录中。

There must be some confusion in passing argument. 传递论点一定会有一些混乱。 You should try to pass absolute path of input file. 您应该尝试传递输入文件的绝对路径。

Below is your modified application. 以下是修改后的应用程序。 This will create One test file and use it instead of asking file name for Case 1. For case 2, it use file which doesn't exist.(Delete if present) 这将创建一个测试文件并使用它,而不是询问案例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 created\n";
    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 present\n";
    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;
}

Note: Construct of std::ifstream always create object. 注意: std::ifstream构造始终创建对象。 You need to its object either as you did or is_open() method. 您需要像以前一样使用它的对象或使用is_open()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用“ifstream”,“stringstream”和“rdbuf()”将文件内容读入字符串时如何检查I / O错误? - How to check for I/O errors when using “ifstream”, “stringstream” and “rdbuf()” to read the content of a file to string? 如何正确使用ifstream从输入文件读取数据? - How do I read data from an input file using ifstream correctly? 将ifstream对象传递给函数后,如何从输入文件中读取? - How do I read from an input file after passing the ifstream object to a function? 如何在C ++中使用ifstream打开和读取文件? - how do I open and read a file using ifstream in C++? 当我打开文件名在 std::string 中的 fstream 时,为什么会出现“无匹配函数”错误? - Why do I get a "no matching function" error when I open an fstream with the file name in a std::string? 为什么我通过ifstream&时会出错? - why am I getting an error when I pass an ifstream&? 为什么我得到一个<incomplete type> gdb 中 ifstream 对象的消息? - Why do I get an <incomplete type> message for a ifstream object in gdb? 为什么在尝试输出字符串时出现此错误? - Why do I get this error when trying to output a string? 为什么将字符串作为文件名而不是char *传递时出现错误? - Why do I get an error when passing a string as a filename, but not a char*? 我可以获取ifstream / ofstream使用的文件名吗? - Can I get the name of file used from ifstream/ofstream?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM