读取数据库/文件中的不同数据类型(c++中的文件处理)

Reading different data types in database/file(File Handling in C++)

本文关键字:文件 c++ 处理 数据类型 数据库 读取      更新时间:2023-10-16

我正在做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。

如果你有任何问题就问!