读取数据库/文件中的不同数据类型(c++中的文件处理)
Reading different data types in database/file(File Handling in C++)
我正在做ATM练习。在我的数据库或"。txt"文件中,我有基本信息。
0123456789 John Doe 0123 9000
我在网上能找到的唯一的东西,在C++中阅读文件是使用getline();
。它读取文件并将其存储在一个可变字符串中。我需要用到整数和浮点数这样的值。
- 如何将数据库中的值存储到不同的数据类型而不是只在一根弦上?
- 或者是否有一种方法可以切割字符串并将不同的值存储在浮点数或整数中?
- 有其他的阅读方式吗?我刚开始学c++编程。
在c++中,你可以通过"file stream"来读取文件:
#include <iostream>
#include <string>
using namespace std;
int main(){
string filename="test.txt";
ifstream fin(filename);
while (!fin.fail()){//read until end of file
int a,d,e;
string b,c;
fin>>a>>b>>c>>d>>e;//That's a line
cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<" n";//show it on command line
}
fin.close();
return 0;
}
您可以使用#include <fstream>
库。下面是它在您的情况下的代码。在"Text.txt"中,我复制并粘贴了您的输入文件。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int firstNumber, thirdNumber, fourthNumber;
string firstString, secondString;
//Reading from a file
ifstream file;
file.open("Text.txt", ios::in);
if (file.is_open()) {
while (!file.eof()) {
file >> firstNumber >> firstString >> secondString >> thirdNumber >> fourthNumber;
cout << firstNumber << " " << firstString << " " << secondString << " " << thirdNumber << " " << fourthNumber << endl;
}
file.close();
}
else {
cout << "File did not open";
}
//Outputing to a file
ofstream file2;
file2.open("SecondText.txt", ios::out); // ios::out instead of ios::in
if (file2.is_open()) {
file2 << firstNumber << " " << firstString << " " << secondString << " " << thirdNumber << " " << fourthNumber;
file2.close();
}
else {
cout << "Problem with SecondText.txt";
}
return 0;
}
这段代码基本上表明,在打开文件时,而不是在文件末尾,按照该顺序为文件中的每一行检索Integer、String、String、Integer和Integer。
如果你有任何问题就问!
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到