c++ - 从文本文件中读取一行时,开头出现额外字符
问题描述
我绝对无法理解读取行开头的多余字符来自哪里。
主要的:
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...
第一张截图
第二张截图
解决方案
您不需要使用指针来存储rows
:
size_t *OldRows = new size_t;
*OldRows = matrix.rows;
简单地说,这会起作用:
size_t oldRows = matrix.rows;
对于读取文件,您可以使用std::stringstream
andstd::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;
}
推荐阅读
- javascript - 防止 jQuery 高级新闻代码中的循环(分叉/修改)
- r - 在插入符号包中使用 LASSO 回归进行归一化会返回奇怪的结果
- apache - 如何在 AEM 中使用具有上下文感知配置的运行模式
- python - 从调用python脚本的java程序接收数据太慢
- python - 如何根据特定元素获取列表元素的所有组合?
- c# - Signalr服务端调用服务点方法返回值
- c# - 确定给定的 url(来自字符串)是否来自我的域
- amazon-web-services - 如何以编程方式检查 Spark 步骤状态(在 EMR 集群上提交)?
- bash - ZSH:找不到命令
- sql - 选择给定专家的最后一次约会和导致它的转诊