c++ - 该程序不会读取整个文件
问题描述
这是一个奇怪的问题,但我编写了一个代码,它从一个充满数字的文本文件中读取字符串并将它们转换为整数。该文件包含400 numbers
并且程序只读392
。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string line;
ifstream read;
int a[20][20];
vector<int>v;
int m;
string y;
string lines [20] ;
read.open("/Users/botta633/Desktop/Untitled.txt",ios_base::binary);
while (read>>line){
y="";
for (int i=0; i<line.length(); i++) {
y+=line[i];
}
m=stoi(y);
v.push_back(m);
}
for (int i=0; i<20; i++) {
for (int j=0; j<20; j++) {
int k=i*20+j;
a[i][j]=v[k];
}
}
for (int i=0; i<20; i++) {
for (int j=0; j<20; j++) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<v.size()<<endl;
return 0;
}
当我尝试更改文件中的整数数量时,它也只读取了其中的一些。
文件看起来像这样
89 41
92 36
54 22
40 40
解决方案
- 您的文件是UTF-8 编码的。它包含不间断的空格 (
C2 A0
),它们被解释ifstream
为非空白和非数字。因此,它停止读取。用西方编码保存它 - 编辑器将用空格替换不间断的空格。 - 这是您读取整数文件的方式:
// source
ifstream is("full_path"); // open the file
// OR, if wide characters
// wifstream is("full_path"); // open the file
if (!is) // check if opened
{
cout << "could not open";
return -1;
}
// destination
vector< int > v;
// read from source to destination - not the only way
int i;
while (is >> i) // read while successful
v.push_back(i);
cout << v.size();
推荐阅读
- android - 用户如何只能在 Cloud Firestore 中看到自己的数据?
- dependency-injection - 清洁架构 - 将应用服务注入另一个应用服务
- c# - 如何在使用时计算数据流(.Net Stream)的长度
- google-cloud-platform - gcp dag 从执行时间中提取年月日期和小时
- javascript - 如何在节点 js 中计算本地时间
- java - 如何使用 SpringBoot 和 React 从 PostGreSQL 数据库中最有效地加载图像
- java - 使用转换将 200M 记录从源模式迁移到目标模式
- python - NumPy 中数组的形状
- reactjs - 无法访问函数中的道具
- json - ansible, jinja2, json - 在 Jinja 中使用 json_query?