首页 > 解决方案 > 该程序不会读取整个文件

问题描述

这是一个奇怪的问题,但我编写了一个代码,它从一个充满数字的文本文件中读取字符串并将它们转换为整数。该文件包含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  

标签: c++stringmultidimensional-arrayvectorstream

解决方案


  1. 您的文件是UTF-8 编码的。它包含不间断的空格 ( C2 A0),它们被解释ifstream为非空白和非数字。因此,它停止读取。用西方编码保存它 - 编辑器将用空格替换不间断的空格。
  2. 这是您读取整数文件的方式

// 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();

推荐阅读