Link to home
Start Free TrialLog in
Avatar of trubiat
trubiat

asked on

How can I read txt file

I need to read a txt file that contains the following data:

61 56 56 47 39 58 4 22

Basically it has 3 lines with different numbers, all separated by single space.

I have tried fgetc but it doesn't seem to work. I would prefer using basic C/C++ functions or commands.
ASKER CERTIFIED SOLUTION
Avatar of nagubala
nagubala

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mnashadka
mnashadka

In C++, use the ifstream file stream class, and the stream extraction operator >>.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  int numbers[9] = {0};
  ifstream input("c:\\input.txt");
  input >> numbers[0] >> numbers[1] >> numbers[2]
        >> numbers[3] >> numbers[4] >> numbers[5]
        >> numbers[6] >> numbers[7] >> numbers[8];
  return 0;
}

Good luck.
If you want to use basic C functions why don't you ask in the C group?

Anyway, fgetc() should work fine, when you get a digit, start saving them in a buffer, when you then get a non-digit you do atoi() on that buffer and save the value and then you scan past the non-digits until next digit etc. stop when EOF is read.

Alf
If you want to read in, it will be easier if you read into an array (looking at mnashadka's example). To do this, you can simply use a loop.

for (int i = 0, i < num_elements - 1, i++)
{
    cin>>numbers[i];
}

where num_elements is the number of numbers you are trying to read in, and numbers is the array that you will store them to.
This question has been abandoned. I will make a recommendation to the moderators on its resolution in a week or two. I appreciate any comments that would help me to make a recommendation.

In the absence of responses, I may recommend DELETE unless it is clear to me that it has value as a PAQ. Silence = you don't care.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Udil
EE Cleanup Volunteer
Avatar of Kyle Abrahams, PMP
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Accept  nagubala answer.

Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Ged
EE Cleanup Volunteer