access variable outside for loop/function

how do i access a variable initialized in a for loop or a function outside of it?
in the code below, i can only cout name inside of the for loop. how can i get it to
print name outside the loop?
1
2
3
4
5
6
7
8
9
10
for (int i = 0; i < arraySize; i++)
    {   int firstComma, secondComma, thirdComma;
        string row = array[i];
        firstComma = row.find(",");
        int weight = stoi(row.substr(0, firstComma-1));
        secondComma = row.find(",", firstComma+1);
        string color = row.substr(firstComma+2, secondComma -1);
        string name = row.substr(secondComma+2);
        cout << name << endl;
    }
Just declare name outside the for loop.
weight, color and name can only be accessed within the loop. Often in cases like these you'd use a struct of the required elements and have it populated by the extract function. This struct would be defined outside of the loop. Or have a function that takes a std::string arg and parses it into a returned struct.

Consider (not tried):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct Extract {
    int weight {};
    std::string color;
    std::string name;
}:

Extract getData(const std::string& row) {
    const auto firstComma {row.find(",")};
    const auto secondComma {row.find(",", firstComma+1)};

    Extract data;

    data.weight = stoi(row.substr(0, firstComma-1));
    data.color = row.substr(firstComma+2, secondComma -1);
    data.name = row.substr(secondComma+2);
    return data;
}


Then if you want access to the last Extract from the array then:

1
2
3
4
Extract data;

for (int i = 0; i < arraySize; ++i)
    data = getData(array[i]);


But often you'd have say a std::vector of Extract and populate the vector. Something like:

1
2
3
4
5
6
std::vector<Extract> data;

for (int i = 0; i < arraySize; ++i)
    data.push_back(getData(array[i]));

// Use data here as required 


Last edited on
thanks a lot. that was very helpful.
Topic archived. No new replies allowed.