C ++显示文本文件...(“回显”文本文件)

时间:2013-07-19 16:08:12

标签: c++ file-io fileinputstream readfile

所以我真的很难在程序中找出这个错误,阻止我显示我的程序文本..

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
using namespace std;

int main ()
{
ifstream infile;
ofstream offile;

char text[1024];
cout <<"Please enter the name of the file: \n";
cin >> text;

infile.open(text);

string scores; // this lines...

getline(infile, scores, '\0'); // is what I'm using...

cout << scores << endl; // to display the file...

string name1;
int name2;
string name3;
int name4;
infile >> name1;
infile >> name2;
infile >> name3;
infile >> name4;

cout << "these two individual with their age add are" << name2 + name4 <<endl;

// 23 + 27

//the result I get is a bunch of numbers...

return 0;

}

有什么方法可以用来显示文件的更简洁的方法吗?

互联网上的所有方法都很难理解或跟踪 该文件循环打开..

我想要一个程序,您键入文件的名称并显示该文件 该文件将包含以下内容......

jack 23 
smith 27

此外,我需要从文件中获取数据,现在我正在使用上面的代码从文件中获取该信息......

2 个答案:

答案 0 :(得分:1)

循环可能是你能做的最好的事情。 所以,如果您知道格式,您可以像这样做

#include <iostream>
#include <fstream>
using namespace std;
int printParsedFile(string fileName) {  // declaration of a function that reads from file passed as argument
    fstream f;     // file stream
    f.open(fileName.c_str(), ios_base::in);     // open file for reading
    if (f.good()) {     // check if the file can be read
        string tmp;     // temp variable we will use for getting chunked data
        while(!f.eof()) {     // read data until the end of file is reached
            f >> tmp;     // get first chunk of data
            cout << tmp << "\t";     // and print it to the console
            f >> tmp;     // get another chunk
            cout << tmp << endl;     // and print it as well

    } else {
        return -1; // failed to open the file
    }
    return 0; // file opened and read successfully
}

你可以调用这个函数,例如在你的main()函数中读取和显示作为参数传递的文件

int main(int argc, char** argv) {
     string file;
     cout << "enter name of the file to read from: "
     cin >> file;
     printParsedFile(file);
     return 0;
}

答案 1 :(得分:0)

我个人使用stringstreams一次读取一行并解析它:

例如:

#include <fstream>
#include <stringstream>
#include <string>

std::string filename;

// Get name of your file
std::cout << "Enter the name of your file ";
std::cin >> filename;

// Open it
std::ifstream infs( filename );
std::string line;

getline( infs, line );

while( infs.good() ) {
    std::istringstream lineStream( line );
    std::string name;
    int age;
    lineStream >> name >> age;
    std::cout << "Name = " << name << " age = " << age << std::endl;

    getline( infs, line );
}