C++ 从文件中读取数据(书籍练习)

C++ Reading Data from a File (Book Exercise)

免责声明:此问题与教科书上的编程练习直接相关。

我正在根据教科书进行 C++ 编程练习,但不知道如何让它工作。希望有人能指出我的代码中的错误。问题来了...

"Use an istream_iterator, the copy algorithm and a back_inserter to read the contents of a text file that contains int values separated by whitespace. Place the int values into a vector of ints. The first argument to the copy algorithm should be the istream_iterator object that's associated with the text file's ifstream object. The second argument should be an istream_iterator object that's initialized using the class template istream_iterator's default constructor - the resulting object can be used as an "end"迭代器。读取文件内容后,显示结果向量的内容。"

我构建了以下代码。代码编译,但不执行任何操作。

int main()
{
    std::vector< int > testVector;

    std::ifstream inputFile( "/Users/GrinNare/Documents/Study/C++/Chapter 16/Chapter 16/16_10_Text_File.txt", std::ios::in );

    std::istream_iterator< int > inputFromFile( inputFile );

    std::copy( inputFromFile, std::istream_iterator< int >(), back_inserter( testVector ) );

    for ( int i = 0; i < testVector.size(); i++ )
        std::cout << testVector[i] << "\t";

    std::cout << std::endl;

    return 0;
}

文本文件包含以下内容: “12 23 43 34”

我尝试调试代码并注意到文本文件中的值没有正确读入 int 向量,因为它们是由空格而不是换行符分隔的。

有人能帮忙吗?!

我在 ideone 中试过你的代码,改为从 std::cin 读取。 It works as expected.

我重现您的问题的唯一方法是使用无法作为输入打开的文件。

所以我想添加以下内容将显示发生了什么:

// after opening the file
if (! inputFile) {
  std::cerr << "Failed to open file" << std::endl;
  return 1;
}

可能你在那个路径中有错字。