0

所以我真的被困在试图找出程序上的这个错误,它阻止我显示我的程序文本..

#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

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

4

2 回答 2

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;
}
于 2013-07-19T16:35:41.903 回答
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 );
}
于 2013-07-19T16:20:58.397 回答