gpt4 book ai didi

C++ 显示文本文件... ("Echo"文本文件)

转载 作者:行者123 更新时间:2023-11-28 07:30:52 25 4
gpt4 key购买 nike

所以我真的一直在试图找出程序中阻止我显示程序文本的错误..

#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

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

最佳答案

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

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

关于C++ 显示文本文件... ("Echo"文本文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17750699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com