简体   繁体   中英

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

I am doing an ATM exercise. In my database or ".txt" file I have the basic information.

0123456789 John Doe 0123 9000

The only thing I can find in the internet, reading a file in C++ is using getline(); . It reads the file and stores it in a variable string. I have values like integer and float which I have to use.

  • How do I store the values in my database to a different data type not just in one string?
  • Or is there a way of cutting the string and store the the different values in a float or integer?
  • Is there another way of reading? I am just new to C++ programming.

You can use the libary #include <fstream> . Here's a code of what it will look like in your case. In "Text.txt" I copied and pasted your inputfile.

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

}

This code basically states that while open, and not at the end of the file, retrieve an Integer, String, String, Integer, and Integer, in that order for every line in that file.

If you have any questions just ask!

In C++,you can read file by "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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM