gpt4 book ai didi

c++ - 使用 fstream 对象将文件中的信息存储到变量中

转载 作者:行者123 更新时间:2023-11-28 00:53:11 24 4
gpt4 key购买 nike

我有以下代码块,用于读取以下格式的文本文件:

firstname lastname id mark
firstname lastname id mark

以下是代码块。

void DBManager::ReadFile(void){
fstream myfile; /*fstream object that will be used for file input and output operations*/
char* fn; /*pointer to the storage which will hold firstname*/
char* ln; /*pointer to the storage which will hold lastname*/
int id; /*integer var to hold the id*/
float mark; /*float var to hold the mark*/

/*read in the filename*/
g_FileName = new char[1024]; /*allocate memory on the heap to store filename*/
cout << "Please enter the filename:";
cin >> g_FileName;

/*open file*/
myfile.open(g_FileName, ios::in | ios::out);

if(myfile.is_open()){ /*check if the file opening is successful*/
cout << "File reading successful !\n";

/*read information from the file into temporary variables before passing them onto the heap*/
while (!myfile.eof()) {

fn=(char*) new char[1024];
ln=(char*) new char[1024];
myfile >> fn >> ln >> id >> mark;
cout << fn << " " << ln << " " << id << " " << mark << " " << endl;

}
myfile.close();
}
else{ /*else print error and return*/
perror("");
return;
}

上面的代码块有效! :)但令我惊讶的是 myfile 如何知道它应该一次保存一行,以及它如何足够聪明地设置四个变量。

我是 C++ 的新手,因此这可能包含在某种文档中。但我很乐意从您那里获得一些见解或指向我可以更好地理解 fstream 对象的地方的链接。

最佳答案

在 C++ 中,std::fstream 是一种专门用于文件的流。从文件读取时,std::fstream 的接口(interface)几乎与 std::cin 相同。输入流被编程为在使用 >>> 运算符询问时读取下一个单词或数字。他们知道单词和数字在哪里,因为它们被空格隔开。在默认语言环境中,空格、制表符和换行符被视为空白。您可以更改语言环境以包含其他字符,例如逗号,并在读取文件时跳过这些字符。基本上,当使用输入流读取时,换行符和空格被视为相同。

这里有一些关于流的很好的解释:http://www.cprogramming.com/tutorial/c++-iostreams.html

关于c++ - 使用 fstream 对象将文件中的信息存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12922992/

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