<pi*****@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Lind Apr 13, 6:32 am show options
Newsgroups: comp.lang.c
From: piss...@gmail.com (Lind) - Find messages by this author
Date: 13 Apr 2005 06:32:15 -0700
Local: Wed,Apr 13 2005 6:32 am
Subject: how to read it out using c++
Reply | Reply to Author | Forward | Print | Individual Message | Show
original | Remove | Report Abuse
8->line 1
30 150
150 30
150 150
30 30
60 120
120 120
120 60
60 60
0 2 1 -3 4 7 6 -5->line2
this is what I have in my poly.dat
I'm quite confused on how to seperate it
I want to read my line1 data as an integer and line2 data should be
put into array which will be used for later code
and the rest line into multidimensional array because each line
represents an (x,y) of a point.
Can anyone figure this out?
What you are trying to do is standard practice. That's assuming you've
bothered reading up on std::strings, std::ifstreams, std::vector and the
like. Why not build a Document class that parses the document for you?
Instead of a vector of ints, you could write a class to hold an x and y
coordinate.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using std::string;
int main(int argc, char* argv[])
{
// A std::istream opens the specified file:
const string s_file = "poly.dat";
std::ifstream ifs;
ifs.open(s_file.c_str(), std::ios::in);
if(!ifs)
{
// error check or throw
std::cout << "error: can't open file.";
return -1;
}
// then read the first line which represents a record count
// (using std::getline).
// load the record count into n_count.
string s_input;
int n_count;
std::getline(ifs, s_input, '\n');
n_count = atoi(s_input.c_str());
// Now you have the record count
std::vector<int> vn; // container
string s; // temp string
int n_x; // left value
int n_y; // right value
int n_seperator; // space locator for parsing
int n_length; // end locator for parsing
for (int i = 0; i < n_count; i++)
{
std::getline(ifs, s_input, '\n'); // collect data string
// locate the space between numbers and end of data
n_seperator = s_input.find_first_of(' ');
n_length = s_input.length();
// parse s_input, load vector
s = s_input.substr(0, n_seperator);
n_x = atoi( s.c_str() );
vn.push_back(n_x);
s = s_input.substr(n_seperator + 1, n_length);
n_y = atoi( s.c_str() );
vn.push_back(n_y);
}
// display
for (i = 0; i < n_count; i++)
{
std::cout << "x[" << i << "]\t";
std::cout << vn[i * 2];
std::cout << "\ty[" << i << "]\t";
std::cout << vn[i * 2 + 1];
std::cout << "\n";
}
return 0;
} // main