Click here to Skip to main content
15,891,763 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a file in which the numbers are written in this form.
2 3
3 4
5 8
1 2

While I am able to get a single line from the file by this method,
XML
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
    }
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}


but what I am looking for is to store the integers from the first column in an array and the integers from the second column in the second array? How can that be done?
Posted

you can try something like this for parsing the line:

#include <vector>

int main ()
{
  string line;
  int iFirstValue;
  int iSecondValue;
  vector<int> vecFirst;
  vector<int> vecSecond;
  
  ifstream myfile ("example.txt");

  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
       getline (myfile,line);

       if (sscanf(line.c_str(), "%d %d", &iFirstValue, &iSecondValue) == 2)
       {
          vecFirst.push_back(iFirstValue);
          vecSecond.push_back(iSecondValue);
       }
    }
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}


Instead of getline() and sscanf() you can also read values directly into the iFirstValue and iSecondValue using stream operators.
 
Share this answer
 
v4
As far numbers are separated by spaces and are always granted to be 2 per line,there is no need to read lines, just read two integers ad push them into the vectors. And repeat until it goes.

C++
#include <vector>
#include <fstream>
#include <iostream>
int main()
{
    using namespace std;
    vector<int> v1, v2;
    ifstream file("example.txt");
    while(!!file)
    {
        int a, b;
        file >> a >> b;
        v1.push_back(a);
        v2.push_back(b);
    }
    cout << "v1 = (";
    for(vector<int> iterator i=v1.begin(), end=v1.end(); i!=end; ++i)
        cout << *i << ' ';
    cout ')' << endl <<"v2 = (";
    for(vector<int> iterator i=v2.begin(), end=v2.end(); i!=end; ++i)
        cout << *i << ' ';
    cout ')' << endl;
    return 0;
}
 
Share this answer
 
Comments
Richard MacCutchan 21-Dec-10 15:49pm    
Never assume that the input you expect is the input you will get. You should read input one line at a time and then parse the content to check it's validity before converting to your destination values.
T2102 21-Dec-10 18:24pm    
I second that, otherwise it's easy to crash your program. I also would suggest that you might use deque or stack instead of vector unless your file knows the number of rows should be within a small interval. In that case, you should reserve some space to start with, keep track of how many elements you fill, and only extend the deque/stack/etc. once it is filled.
Emilio Garavaglia 22-Dec-10 2:48am    
To Richard: in general true, but why, why, why STL has istreams and the >> operators ?? If this wants to be an exercise about the STL, I was just demonstrating that can be done. If it is production code, than this is just one of the many "don't use iostreams" issue that can arise (see "http://yosefk.com/c++fqa/io.html")

To Ted: There is no way to crash that program. It will simply stop reading. I can agree with you in general term, but this is not the context. About deque and stack, it mostly depend on the implementation. What vector does when something is pushed back -in the implementation that are not 10 years old- is grow estimating the future grow as 50% of the actual size. There is no need to know in advance the number of elements (and reading the file twice just to know how many elements it has may be less efficient then letting a vector (deque or stack are the same) to grow dynamically.
See "http://www2.research.att.com/~bs/bs_faq2.html#simple-program"
and "http://www.google.it/url?sa=t&source=web&cd=3&sqi=2&ved=0CD8QFjAC&url=http%3A%2F%2Fwww.stroustrup.com%2FProgramming%2F19_vector.ppt&rct=j&q=stroustrup%20vecto&ei=f6wRTcq6LYb94AathbmGAg&usg=AFQjCNHpvFq2V6C6HwugV5Tfq8zxRPOIQA&sig2=iLw-yKGNas_F77icJ57tDg&cad=rja"

Deque does exactly the same (the difference is that free space is placed on both sides, so that you can grow either in front and in back). Stack is not a container: it wraps other container (usually a vector) by forcing it to have just pop and push. All those containers use the same mechanism to manage memory.
One more way to use vector in your code is :

C++
struct data
{
  int iVal1;
  int iVal2;
};

vector <data> vcData;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900