如何读取一个表从.txt文件到C ++ [英] How to read a table from .txt file to C++

查看:125
本文介绍了如何读取一个表从.txt文件到C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件中读取一个矩阵,并在我的程序中使用它。但是当我输出结果时,表明它没有正确读取。
这是代码:

I want to read a matrix from a file and use it in my program. but when I output the results, it shows that it is not reading correctly. Here is the code:

#define I 5 
#define J 5 
#define P 2 

int i,j,k;  //for loops

int main ()
{
    ifstream inFile;
    ofstream outFile;
    double C[I][J];

    inFile.open("C.txt", ios::in);
    if (! inFile) {
        cerr << "unable to open file C.txt for reading" << endl;
        return 1;
    }

    for(i=0; i<I; i++)
        for(j=0; j<J; j++)
            inFile >> C[i][j];

    outFile.open("results.txt");
    outFile<< "C" <<endl;
    for(i=0;i<I;i++)
    {
        for(j=0;j<J;j++)
            outFile<< C[i][j];
        outFile<< endl;
    }

    inFile.close();
    outFile.close();

    return 0;
}

C是整数值的矩阵2 3 5 ...但是, get是

C is a matrix of integer values 2 3 5... but what I get is


316-9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + 061
- 9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + 061 -9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + 061- 9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + 061 -9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + 061-9.25596e + / p>

316-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061


推荐答案

您应该在每个数字后输出一个空格,否则它们都会粘在一起。

You should output a whitespace after each number, otherwise they will be all glued together.

outFile<< C[i][j] << " ";

您还应检查输入的有效性。在此不显示(您已经知道如何检查 if(!inFile))。

You also should check your input for validity. Not showing it here (you already know how to check if (! inFile)).

这篇关于如何读取一个表从.txt文件到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆