Home > Software engineering >  error: std::string was not declared in this scope, in for loop C
error: std::string was not declared in this scope, in for loop C

Time:11-12

I was trying to implement code making use of the GMP library for a class, and haven't been able to figure out the source of this issue. I've run similar code before on an unordered_map so this error is confusing me. From what I can tell the std::string should be declared in the scope by the call to the for loop. Could it be related to using the GMP library?

int main(int argc, char** argv){
std::map<mpz_class, std::string> number_names;
std::ifstream names_file("/srv/datasets/number_names.txt");
if(!names_file.is_open()){
  std::cout << "error reading /srv/datasets/number_names.txt\n";
  return -1;
}
mpz_class num;
for (std::string name : names_file >> name >> num){ // line throwing error
  number_names[num] = name;
}
auto value = mpz_class(argv[1]);
std::vector<std::string> output = some_func(value, number_names);

}

the full error message reads:

    as10.cpp:75:43: error: ‘name’ was not declared in this scope 
    75 |     for (std::string name : names_file >> name >> num)

CodePudding user response:

for (std::string name : names_file >> name >> num){
  number_names[num] = name;
}

This is not how range-based for loop works in C , so this is a syntax error. By the looks of it, you have a typo.

Maybe what you want is:

std::string name;
while(names_file >> name >> num){
    number_names[num] = name;
}

Or:

for (std::string name; names_file >> name >> num;){
    number_names[num] = name;
}
  • Related