Jump to content

How to read all next line in file?

- - - - -

  • Please log in to reply
3 replies to this topic

#1
Hamed

Hamed

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts
I have file by the name:A.in

it have txt format like:

12 12 12 12 12
3 3 3 3 3
12 12 12 12 12
23 23 23 23 23

I use this code to read 1st line how can read other line with line number/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    int a,b,c,d,e;
    ifstream myfile("A.in");
    myfile>>a>>b>>c>>d>>e;
    cout<<a+b+c;
    system("pause");
    return 0;
}


#2
AdvMutant

AdvMutant

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 438 posts
Hmm... Maybe you can use fgets()?
The declaration looks like so -

Quote

fgets( char*, size_t, file_stream );
Read more about it here. All the mentioned functions are in "stdio.h".

Posted Image
There is no problem that cannot be solved by the use of high explosives.


#3
Hamed

Hamed

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts
I want to do it with ifstream if possible!


#4
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200

Hamed said:

I want to do it with ifstream if possible!

This should work:
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    int a,b,c,d,e;
    ifstream myfile("A.in");
    char line[255];
     
    while(myfile.getline(line, 255)) {
        myfile >> a >> b >> c >> d >> e;
        cout << (a + b + c) << endl;
    }

    system("pause");
    return 0;
}

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users