2

I am reading in a file of the format:

12, 10
15, 20
2, 10000

I want to read these in as x,y points. I've started out, but I'm not sure where to proceed from here... Here is what I have so far:

ifstream input("points.txt");
string line_data;

while (getline(input, line_data))
{
    int d;
    std::cout << line_data << std::endl;
    stringstream line_stream(line_data);
    while (line_stream >> d)
    {
        std::cout << d << std::endl;
    }
}

How can I read each of these lines in as an x,y integer?

zebra
  • 6,373
  • 20
  • 58
  • 67

3 Answers3

6

Say:

int a, b; char comma;

if (line_stream >> a >> comma >> b)
{
  // process pair (a, b)
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

what about this ?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    std::ifstream input("points.txt");

    while (!input.eof())
    {
        int x, y;
        char separator;

        input >> x  >> separator >> y;

        cout << x << ", " << y << endl;
    }
}
n1r3
  • 8,593
  • 3
  • 18
  • 19
  • 1
    [This is not a good practice.](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Blastfurnace Dec 19 '11 at 21:46
  • Please don't encourage the use of `ios::eof` as a loop condition. Doing so almost always results in buggy code. Prefer `while(input >> x >> separator >> y)`. – Robᵩ Dec 19 '11 at 21:48
1
ifstream input("points.txt");
int x, y;
char comma;
while (input >> x >> comma >> y)
{
    cout << x << " " << y << endl;
}
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110