0

I am trying to learn C++ ifstream i came across this code on the net and have some question.

void read() {
    ifstream  inFile ("in.txt");
        string  l, i;
        int item = 0;

        while (getline (inFile, l)) { // is this one checking end of file like java?

        istringstream linestream(l); // what does this one do?
        while (getline (linestream, i, ' ')) {

            item++;
            if (item <= 3) {
                initial.push_back(atoi(i.c_str()));
                                                  //atoi(i.c_str()) what is this?
                                                  // initial is a vector like ArrayList in java
            }
            else {
                final.push_back(atoi(i.c_str()));
            }
        }
    }

Thanks

Edited by Reverend Jim: Fixed formatting

2
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by banh
0

I am trying to reference it to Java so I can understand it better.
the initial is

vector<int> initial;

it works very similar to Java ArrayList, but other than that I need help explaining the rest.

0

Unfortunately I don't know Java, but you can get a good idea from here:
http://www.cplusplus.com/reference/stl/vector/

If you initialize it like you have done, it will have 0 elements. Using push_back(element) will extend the vector and insert the element in the last position. Once the vector has some contents, you can access elements with initial.

Several other things you can do with vectors are shown here:
http://programmingexamples.net/index.php?title=CPP/STL/Vector

David

0

Thanks
quick question

void read() {
      ifstream inFile ("in.txt");
      string l, i;
      int item = 0;
 
      while (getline (inFile, l)) { 
         istringstream linestream(l);
         while (getline (linestream, i, ' ')) {
             item++;
             if (item <= 3) {
                  initial.push_back(atoi(i.c_str()));
                                   //atoi(i.c_str()) what is this?
                                   // initial is a vector like ArrayList in java
         }
         else {
         final.push_back(atoi(i.c_str()));
     }
  }
}

say if I have the input file:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18

the final result in initial = {1,2,3} type Integer
and final = {4,5,6} type Integer
if both final and initial are vector<int>

0

Just trying to understand what the code does if have the "in.txt" as above.

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.