C++从文本文件读取到数组/字符串

5

以下是我目前的代码。

我需要做的是从两个不同的文本文件 Matrix A 和 Matrix B 中读取数据。

我可以做到这一点,但是每次读取一个文本文件矩阵时,只会得到如下结果:

1 0 0 

所以基本上第一行是指,矩阵A的整个文本文件实际上是

1 0 0
2 0 0
3 0 0

有人知道我该如何做到这一点吗?

谢谢!

#include <iostream>  //declaring variables
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;
string code(string& line);
int main()
{
    ofstream outf;
    ifstream myfile;
    string infile;
    string line;
    string outfile;

    cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
    cin >> infile;   //prompts user for input file

    if (infile == "A.txt")
    {      //read whats in it and write to screen
        myfile.open("A.txt");
        cout << endl;
        getline (myfile, line);
        cout << line << endl;

    }
    else
        if (infile == "B.txt")
        {
            myfile.open("B.txt");
            cout << endl;
            getline (myfile, line);
            cout << line << endl;
        }
        else
    { 
        cout << "Unable to open file." << endl;
    }
        //{
            //while("Choose next operation");
        //}
    return 0;
}
3个回答

9

显然,getline 函数会获取一行。

你应该逐行读取直到文件结尾,你可以通过下面的代码实现:

while (getline(myfile, line))
    out << line << endl;

这意味着:只要还有从myfile中读取的行,就将该行写入输出流中。

英雄!非常感谢你。 - user3536870

2

你只读取了一次,所以这不是奇迹。要进行连续读取,你需要使用while或for循环。你可以写出以下类似的代码:

while (getline (myfile, line))
    cout << line << endl;

这是编写整个代码的全部内容:
#include <iostream>  //declaring variables
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;
string code(string& line);
int main()
{
    ofstream outf;
    ifstream myfile;
    string infile;
    string line;
    string outfile;

    cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
    cin >> infile;   //prompts user for input file

    if (infile == "A.txt")
    {      //read whats in it and write to screen
        myfile.open("A.txt");
        cout << endl;
        while (getline (myfile, line))
            cout << line << endl;


    }
    else
        if (infile == "B.txt")
        {
            myfile.open("B.txt");
            cout << endl;
            while (getline (myfile, line))
                cout << line << endl;
        }
        else
    { 
        cout << "Unable to open file." << endl;
    }
        //{
            //while("Choose next operation");
        //}
    return 0;
}

我是一个编程的初学者,目前遇到了很多困难,所以对于我的一点点知识来说,这并没有太大的意义。如果您能向我展示如何修改代码,那将会帮助我很多。 - user3536870
@user3536870:感谢,但请购买一本C++书籍,例如Bjarne's。此外,请阅读这篇文章,了解如何接受答案。 - László Papp

0

使用getline是最简单的方法:

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

void read_file_line_by_line(){
    ifstream file;
    string line;
    file.open("path_to_file");
    while (getline (file, line))
        cout << line << endl;
}

int main(){
    read_file_line_by_line();
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接