简体   繁体   中英

I/O C++ Reading from a text file

In my program I'm inputting a file and inside the file is something like this:

11267 2 500.00 2.00

...that is one line. There are more lines set up in that same order. I need to input the first number, 11267 , into actnum . After that, 2 into choice , etc. I simply lack the logic to figure out how to input just the first 5 numbers into the first variable.

actnum = 11267;
choice = 2;

Edit*

I have all of that:

#include <fstream>
#include <iostream>
using namespace std;



void main()
{
    int trans = 0, account;
    float ammount, bal;

    cout << "ATM" << endl;

etc etc

I just dont know how to get it to only input the specific numbers into it. Like when I do the >>actnum >> choice how does it know to put just the first 5 numbers in it?

Use the C++ <fstream> library. fscanf() is slightly out of date and you will probably get better performance from <fstream> , not to mention that the code is a lot easier to read:

#include <fstream>
using namespace std;

ifstream fileInput("C:\foo.txt");
fileInput >> actnum >> choice >> float1 >> float2;

fscanf is what you are looking for. it works the same as scanf, but is for files.

unsigned int actnum, choice;
float float1, float2;

FILE *pInputFile = fopen("input.txt", "r");

fscanf(pInputFile, "%u %u %f %f", &actnum, &choice, &float1, &float2);
input_file_stream >> actnum >> choice >> ...

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