0

I'm writing a program that opens a file then sorts it a couple different ways then closes it. Someone in my class said something about using a getline function but I can't figure out how that works. I can't find a way to take a specific line in a text file and then put it into an array. How can I get each number into its own array?

4532 111 2123
324 3211 223
233 4493 992

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

>>but I can't figure out how that works.

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

int main()
{
    ifstream in("filename.txt");
    string line;
    // read each line of the file
    while( getline( in, line) )
    {
          //blabla do something this line
    }
}

>>I can't find a way to take a specific line in a text file
You have to read each line one at a time until you get to the line that you want.


>>How can I get each number into its own array?
What kind of array? int array?

#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    vector<int> arry; // array of integers
    ifstream in("filename.txt");
    int num;
    // read each line of the file
    while( line >> num )
    {
          arry.push_back(num); // add the number to the array
    }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.