Home > Net >  identifier "numIDs" is undefined while inside of scope
identifier "numIDs" is undefined while inside of scope

Time:10-05

I am coding a small app thats supposed to take a string of numbers from a text file then save them into an array, and finally print the array through iteration, the file should be in this format:

10 0 1 2 3 4 5 6 7 8 9

The first number being the amount of numbers or "IDs" that should be in the array, the rest being the elements of this.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream test;
    test.open("test.txt");
    string s;
    getline(test, s);
    int numtest = s[0];
    for (int  i = 0; i < numtest; i  ) {
        string currLine;
        getline(test, currLine);
        int numIDs = currLine[0];
        int arrayIDs[numIDs];
        for (int j = 2, k = 0; j < numIDs; j  = 2, k  ) {
            arrayIDs[k] = currLine[j];
        }
    }
    test.close();
    for (int i = 0; i <= numIDs; i  ) {
        cout << arrayIDs[i];
    }
}

However, i get the errors

identifier "numIDs" is undefined

identifier "arrayIDs" is undefined

On lines 22 and 23 respectively, though i dont know why, to my understanding since these 2 are variables there shouldnt be any problems with an #include, and are both inside the main() function, so i dont get why they would be undefined.

CodePudding user response:

Variables placed inside a loop will not be visible outside the loop. So to fix your problem, declare numIDs outside the loop instead of in it. Also, from the looks of it, you would want to put the second loop in the first. Original:

int numtest = s[0];
for (int  i = 0; i < numtest; i  ) {
    string currLine;
    getline(test, currLine);
    int numIDs = currLine[0];
    int arrayIDs[numIDs];
    for (int j = 2, k = 0; j < numIDs; j  = 2, k  ) {
        arrayIDs[k] = currLine[j];
    }
}

Revised:

int numtest = s[0];
int numIDs = 0;
for (int  i = 0; i < numtest; i  ) {
    string currLine;
    getline(test, currLine);
    numIDs = currLine[0];
    int arrayIDs[numIDs];
    for (int j = 2, k = 0; j < numIDs; j  = 2, k  ) {
        arrayIDs[k] = currLine[j];
    }
    for (int i = 0; i <= numIDs; i  ) {
        cout << arrayIDs[i] << ' ';
    }
}
  • Related