首頁  >  問答  >  主體

文件读取 - C++,使用getline一直读取不到文件中的内容

想试着写一个做矩阵运算的代码,然后发现一直都无法使用getline()从文件中读取矩阵。但是我在别的代码中却可以使用getline(),下面是代码。

#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <vector>

using namespace std;
typedef vector<vector<int>> douvec;

//产生一个含有矩阵的文件,这里能够正常的产生矩阵文件
void create_file (fstream &file) {
    int rank;
    //提示输入产生的矩阵的维度
    cout << "input the rank: ";
    cin >> rank;

    //随机生成矩阵的数值
    srand(time(0));
    for (int r = 0; r < rank; r++){
        for (int c = 0; c < rank; c++)
            file << rand()%2 << " ";
        file << '\n';   
    }

}

//讲文件中的矩阵读入一个二维vector中
auto create_matrix (fstream &file) -> vector<vector<int>> {
    char num;
    string line;
    douvec matrix;

    //这里的getline一直都读取不了文件中的任何的数据
    while (getline(file, line)){
        stringstream record(line);
        vector<int> temp;
        if (line == "")
            break;
        while (record >> num){
            int number = (int)num;
            temp.push_back(number);
        }
        matrix.push_back(temp);
    }
    return matrix;
}

int main(){
    fstream file("file.txt", ofstream::app);
    douvec matrix;
    create_file(file);

    //这里输出的matrix.size()一直都是0
    cout << "matrix size is " << matrix.size() << endl;
    matrix = create_matrix(file);
    for (int row = 0; row < matrix.size(); ++row){
        for (int col = 0; col < matrix[row].size(); ++col)
            cout << matrix[row][col] << "  ";
        cout << endl;
    }

    return 0;

}
黄舟黄舟2764 天前576

全部回覆(1)我來回復

  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:56:26

    使用getline讀不到文件內容是因為不當使用
    兩個問題

    1. 如果想同時讀寫一個fstream應該加上對應mode
      fstream file("file.txt", ofstream::in | ofstream::app);

    2. c++ fstream 其實只是把C FILE I/O 重新包裝而已。
      看c++11 N3337 27.9.1.1

      The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library Standard C libraryo>. —
      If the file is not open for reading the input sequence cannot be read.
      — If the file is not open for writing the output sequence cannot beritten.

      看c11 WG14 N1570 7.21.5.3

      When a file is opened with update mode ('+' as the second or third

      character in the above list of mode argument values),
      both input and


      output may be performed on the associated stream
      . However, outputshall not be directly followed by input without y
      shall not be directly followed by input without out< the fflush function or to a file positioning function (fseek, fsetpos,
      or rewind), and input shall not be directly followed by output without< a file positioning function, unless the input
      operation encounters endof-file. Opening (or creating) a text file
      with update mode may instead instead open create) a bin create) a bin stream in someimplementations.
      所以只要在前面加上

      或其他repositioning就可以了。

      回覆
      0
  • 取消回覆