首页 > 解决方案 > 从文本文件中读取一行时,开头出现额外字符

问题描述

我绝对无法理解读取行开头的多余字符来自哪里。

主要的:

int main(){
    DynamicMatrix Matrix1;
    ifstream f1("matrix.txt", ios::in);
    f1 >> Matrix1;
    cout << Matrix1;
    f1.close();
    return 0;
}

类中的重载运算符:

ifstream& operator>> (ifstream& ifs, DynamicMatrix &matrix){
try{

    size_t *OldRows = new size_t;
    *OldRows = matrix.rows;
    
    if (!ifs.is_open()) throw DynMatrixException("Unable to read this file.");

    char* loaded = new char[1000];

    size_t temp_rows = 0;
    size_t temp_columns = 0;
    int n = 0;
    while (!ifs.eof()) ifs.read(&loaded[n++], sizeof(char));
    loaded[n]='\0';
    //other code
}
catch...

第一张截图

文本文件

第二张截图

结果行

标签: c++

解决方案


您不需要使用指针来存储rows

size_t *OldRows = new size_t;
*OldRows = matrix.rows;

简单地说,这会起作用:

size_t oldRows = matrix.rows;

对于读取文件,您可以使用std::stringstreamandstd::getline逐行读取并存储它。

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    ifstream in("sample.txt");
    if (!in.good())
    {
        cout << "Could not open file\n";
        return 1;
    }
    
    string line;
    stringstream ss;
    
    while (getline(in, line))
    {
        ss << line << endl;
    }
    
    string whole_file = ss.str();
    cout << whole_file << endl;

    return 0;
}

如果要使用 C 风格的字符串,则可以使用istream::get逐个字符读取并存储在字符数组中buffer

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    ifstream in("sample.txt");
    if (!in.good())
    {
        cout << "Could not open file\n";
        return 1;
    }
    
    char* buffer = new char[1024];
    int count = 0;
    
    while (in.get(buffer[count]))
    {
        count++;
    }
    
    for (int i = 0; i < count; i++)
    {
        cout << static_cast<int>(buffer[i]) << "|" << buffer[i] << " ";
    }
    cout << endl;

    delete[] buffer;
    return 0;
}

推荐阅读