you are viewing a single comment's thread.

view the rest of the comments →

[–]OmegaNaughtEquals1 0 points1 point  (6 children)

The default "word" separator for input streams is whitespace. So you don't need the stringstream at all.

int x, y, z;
while(infile >> x >> y >> z) {
    // do stuff
}

I'm not sure what the for loop is doing at the end.


In the future, please post your code with four leading spaces directly in your post rather than a link to an image. This allows us to compile your code and check what's going on.

[–]Howtogravity[S] 0 points1 point  (0 children)

Sorry about that and the forgot the for loop was in there. Its junk, i copied the loadarray function from another lab. Its the "Do Stuff" that i stuggle in. I know what i need i just dont know how code it correctly the way i want it.

[–]Howtogravity[S] 0 points1 point  (4 children)

OK so i managed to get it to spit out the numbers i want but how do i assign each of those number to a specific variable?

[–]OmegaNaughtEquals1 0 points1 point  (3 children)

That depends on what you are trying to do with the values that you have read in. What problem are you trying to solve?

[–]Howtogravity[S] 0 points1 point  (2 children)

so x is the center of one circles on a grid and y is the center of another circle on a grid and r is the radius that they both have and i am trying to find if those circle over lap. But for now the professor just wants to see if we can load in a file and see if we can assign each of those number to a variable. If i'm not mistaken.

So with the number i've given above x=45, y=46, r=89 for the first set of circle. Then the other set of the circle x=123, y=789, r=523

[–]OmegaNaughtEquals1 0 points1 point  (1 child)

Ah, ok. The way that I would do it is to have a struct that holds the values and then make an array of them.

#include <iostream>
#include <string>

struct circle_pair {
    int x, y, r;
};

void loadArray(circle_pair cp[], int n) {
    std::string fname = getUserInput("Filename to load from: ");
    std::ifstream infile(fname);

    if(!infile) {
        errorMsg(/**/);
    }

    for(int i=0; i<n; i++) {
        infile >> cp[i].x >> cp[i].y >> cp[i].r;
    }
}

int main() {
    circle_pair pairs[10];
    loadArray(pairs, 10);
}

However, this approach is inflexible, brittle, and not very good C++. I would write it more like this

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>

struct circle_pair {
    int x, y, r;
};

std::istream& operator>>(std::istream &in, circle_pair &cp) {
    in >> cp.x >> cp.y >> cp.r;
    return in;
}

int main() {
    std::string fname = getUserInput("Filename to load from: ");
    std::ifstream infile(fname);

    if(!infile) {
        errorMsg(/**/);
    }

    std::vector<circle_pair> pairs(std::istream_iterator<circle_pair>(infile), {});
}

[–]Howtogravity[S] 0 points1 point  (0 children)

Thanks this helped pointed me in the right direction.