【问题标题】:the program doesn't read the whole file该程序不会读取整个文件
【发布时间】:2018-12-29 22:21:06
【问题描述】:

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

【问题讨论】:

  • 那里发生了很多事情。我建议缩减并从仅读取文件开始。如果您无法正确读取文件,那么程序的其余部分就不值那么多钱了,而且在修复需要丢弃并重写其他代码的错误时真的很糟糕。真的不值得一次写多于一件事。
  • 为什么不是 int m; while ( 读 >> m ) v.push_back(m);?
  • 当我读入一个整数时,它什么也不读
  • 这可能是因为您使用的是两位数字,并且您使用 line[i] 获取数字。尝试使用单个数字来检查是否是问题所在。

标签: c++ string multidimensional-array vector stream


【解决方案1】:
  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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-02
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多