读取文件并将其输入为整数数组输入

时间:2016-10-14 07:26:32

标签: c++ arrays ifstream hevc libx265

我正在研究HEVC,即X265,在这里,我正在尝试使用从文件中读取的值输入QP数组。我知道qp数组的值将是0到100.

我创建了一个测试文件并输入1和0的组合直到99.文件如下所示:

10101010110101010000000000000000000000000000000000000000000000000000000000000000000000000000000000

我为此目的编写的代码如下:

ifstream myfile;
    myfile.open("/Users/Ahmedrik/Mine/Uni-Stuff/Test-FYP/roi.txt");
    char input[100];
    int qp_input[100];


        while (!myfile.eof()) {
            myfile >> input;
            cout<< input<<endl;
        }myfile.close();


    for(int i=0;i<100;i++){
        qp_input[i]=(int)input[i];
        if(qp_input[i]==48){
            qp_input[i]=1;
        }
        else
            qp_input[i]=0;

        cout<<i<<" : "<<qp_input[i]<<endl;
    }

但我无法拥有正确的价值观。 qp_input保持为0.我做错了什么?

2 个答案:

答案 0 :(得分:2)

检查此解决方案

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <sstream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
    ifstream myfile;
    myfile.open("text.txt");

    int qp_input[100];

    //will read whole contents to a string instead of while(!myfile.eof())
    std::string input( (std::istreambuf_iterator<char>(myfile) ),
                       (std::istreambuf_iterator<char>()    ) );
    for(int i=0;i<input.size();i++){
        stringstream ss;
        ss<<input[i];
        ss>>qp_input[i];
        cout<<i<<" : "<<qp_input[i]<<endl;
    }
}

答案 1 :(得分:0)

在数组中输入并且您试图读入指针“&gt;&gt; input”而不是读入该数组中的数组索引,例如“&gt;&gt;输入[index]”。你应该在你的循环中有一个计数器并读入数组。

    int index = 0;
    while (!myfile.eof()) {
        myfile >> input[index];
        cout<< input[index] <<endl;
        index++;
    }
    myfile.close();

此外,文件中的数据类型。在monent中,您将读取字符,因此假设它们是字节。如果您的结果是纯文本十进制格式,则需要将输入类型更改为int或double。

相关问题