简体   繁体   中英

error: expected unqualified-id before 'for'. compilation terminated due to -Wfatal-errors

I cannot figure out what's wrong. The error is on line 7, as I've commented out. Any help is greatly appreciated.

error: expected unqualified-id before 'for'. compilation terminated due to -Wfatal-errors.

#include <iostream>
#include <map>
#include <math.h>

const char digit_ints[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
std::map<char,int> digit_map; 
for (int i = 0; i < 10; ++i) // ERROR ON THIS LINE!!!!!!!
    digit_map.insert(std::pair<char,int>(digit_ints[i], i));


int str2Int(const std::string& S) { 
    int sz = S.size();
    if (sz == 0) { 
        std::cout << "str2Int() cannot take an empty string as a parameter." << std::endl;
        return -1;
    } else { 
        int sum(0);
        for (int j(0), k(sz - 1); j < sz; --k, ++j) { 
            if ((S[j]) < 0 || (S[j]) > 9) { 
                std::cout << "str2Int can only take strings with chars '0' through '9' as parameters." << std::endl;
                return -1;
            } else { 
                sum += digit_map[S[j]] * pow(10, k);
            }
        }

    }
    return sum;
} 


int main() { 

    std::cout << str2Int("3421");

    return 0

}

What's this for loop doing outside of a function?

for (int i = 0; i < 10; ++i) // ERROR ON THIS LINE!!!!!!!
    digit_map.insert(std::pair<char,int>(digit_ints[i], i));

That certainly is an error. It's not contained inside any function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM