C ++从文本文件读入一个数组/串 [英] C++ reading from a text file into a array/string

查看:143
本文介绍了C ++从文本文件读入一个数组/串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是code我有这么远。<​​/ P>

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

我可以为每个文本文件的矩阵但是做到这一点我读它仅与

出现

  1 0 0

(所以基本上第一线),其中为矩阵的整个文本文件实际上是在

  1 0 0
2 0 0
3 0 0

所以没有任何人知道我能做到这一点?

谢谢!

 的#include&LT;&iostream的GT; //声明变量
#包括LT&;&了iomanip GT;
#包括LT&;串GT;
#包括LT&;&的fstream GT;使用命名空间std;
字符串code(字符串&安培;线);
诠释的main()
{
    的ofstream OUTF;
    ifstream的MYFILE;
    串INFILE;
    串线;
    串OUTFILE;    COUT&LT;&LT; 请输入输入文件(A.TXT)矩阵A或(B.txt)矩阵B&LT;&LT; ENDL;
    CIN&GT;&GT; INFILE; //提示用户输入文件    如果(INFILE ==A.TXT)
    它{//读什么和写入屏幕
        myfile.open(A.TXT);
        COUT&LT;&LT; ENDL;
        函数getline(MYFILE,线);
        COUT&LT;&LT;线474;&LT; ENDL;    }
    其他
        如果(INFILE ==B.txt)
        {
            myfile.open(B.txt);
            COUT&LT;&LT; ENDL;
            函数getline(MYFILE,线);
            COUT&LT;&LT;线474;&LT; ENDL;
        }
        其他
    {
        COUT&LT;&LT; 无法打开文件。 &LT;&LT; ENDL;
    }
        // {
            //而(选择下一个操作);
        //}
    返回0;
}


解决方案

好了,函数getline 显然得到一行。

您应该逐行读取直到文件的末尾,并且可以实现与,例如:

 而(函数getline(MYFILE,线))
    出&LT;&LT;线474;&LT; ENDL;

这意味着:虽然有一条线从MYFILE就搞定了,写一行到输出流

Here is the code I have so far.

What I need to do is read from two different text files, Matrix A and Matrix B.

I can do this however for each text file matrix I read it only comes up with

1 0 0 

(so basically the first line) where the whole text file for Matrix A is in fact

1 0 0
2 0 0
3 0 0

so does anybody know how I can do this?

Thanks!

#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;
}

解决方案

Well, getline obviously gets one line.

You should read line by line until the end of file, and you can achieve that with, for example:

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

This means: while there is a line to get from myfile, write that line to the output stream.

这篇关于C ++从文本文件读入一个数组/串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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