使用 fstream 对象将文件中的信息存储到变量中
using fstream object to store information from a file into variables
我有以下代码块,用于读取以下格式的文本文件:
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
的界面几乎与std::cin
相同。输入流被编程为在>>
运算符询问时读取下一个单词或数字。他们知道单词和数字在哪里,因为它们被空格隔开。在默认区域设置中,空格、制表符和换行符被视为空格。您可以更改区域设置以包含其他字符(如逗号),并在读取文件时跳过这些字符。基本上,当使用输入流读取时,换行符和空格的处理方式相同。
这里有一些关于学习流的很好的解释:http://www.cprogramming.com/tutorial/c++-iostreams.html
我不确定问题是什么。但是,代码存在几个问题:
- 您应该在尝试阅读后始终检查输入。
- 测试
eof()
以确定是否有更多内容要阅读不起作用。 - 您有一个内存泄漏,在每个迭代器中分配内存。
- 在没有约束的情况下读取
char
数组是不安全的,即它容易被缓冲区覆盖(主要的攻击媒介之一)。
你想使用如下所示的循环:
std::string fn, ln;
while (myfile >> fn >> ln >> id >> mark) {
...
}
相关文章:
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- 按字母顺序打印存储在字符数组中的信息
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 对于存储另一个类所需信息的类,例如其构造,是否有设计模式?
- structtm是否将时区信息存储为其数据成员
- 将不同的模板化类存储在一个容器中,而不会丢失有关其类型的信息
- 合法的方式将destructor信息存储到void*
- 为什么类型转换对象不会更改其地址?有关对象类型的信息存储在哪里?
- 为什么C++不使用集中存储类型信息以实现高效的 RTTI
- (C++) 如何从要存储在结构数组中的二进制文件中读取.dat信息?
- 我应该如何存储从文件中获取的这些信息?
- 如何将循环中的信息存储到数组中
- 使用 fstream 对象将文件中的信息存储到变量中
- 数组的指针,该数组的每个元素的内存空间信息存储在哪里
- 将文件中的信息存储在类对象 (C++) 中
- 将switch语句中的信息存储到变量中
- 如何将*.css文件(文本文件)的内容与附加信息存储在新文件中?
- 将矩阵信息存储在STL矢量中.哪个是更好的矢量,哪个是矢量中的矢量
- 用于临时错误信息存储的实用工具类
- 记录器在崩溃后没有将记录的信息存储到文件中