2013-07-19 64 views
0

所以我很坚持努力想通对阻止我我的显示程序的文本程序这个bug ..C++显示一个文本文件......(“回声”的文本文件)

#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 

而且我现在需要我用上面的代码来获得从文件信息从文件中获取数据...

+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()函数来读取和显示文件'非常确定'std :: cout << infile.rdbuf();'会做到这一点。 – chris

+2

这是功课吗? – jwiscarson

+0

std :: cout << infile.rdbuf(); – Cris

回答

0

我个人使用stringstr读取一行的时间和解析它EAMS:

例如:

#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); 
} 
+0

但我想显示该文件..然后显示上面提供的内容...感谢您的简化... – Cris

1

循环可能是你能做的最好的事情。 所以如果你知道的格式,你可以简单地做这样的说法

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

但哪部分将显示文件?我想知道哪个部分会显示文件... – Cris

+0

我用评论更新了它,以便您更好地理解它。基本上,假设你知道你正在阅读的文件中的数据格式(例如,每行有2个值),你可以通过将数据分割成像这样的块来轻松解析它。数据流中的数据将被读取,直到达到值之间的空间,所以您唯一需要做的就是确保数据的格式一致 – mewa