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

时间:2014-04-19 15:55:11

标签: c++ arrays string matrix

这是我到目前为止的代码。

我需要做的是从两个不同的文本文件中读取,即矩阵A和矩阵B.

我可以这样做但是对于我读过的每个文本文件矩阵,它只出现

1 0 0 

(基本上是第一行),其中Matrix 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 个答案:

答案 0 :(得分:9)

好吧,getline显然有一行。

你应该逐行阅读,直到文件结束,你可以用,例如:

来实现
while (getline(myfile, line))
    out << line << endl;

这意味着:虽然有一行从myfile获取,但请将该行写入输出流。

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}