简体   繁体   中英

error: implicit conversion changes signedness: 'int' to 'unsigned long'

I am using clang++ "file.cpp" -std=c++14 -Weverything -Wno-c++98-compat to compile my program. Now I get this following error code:

warning: implicit conversion changes signedness: 'int' to 'unsigned long' [-Wsign-conversion]

The error line is this:

v_rand = rand() % (english.size());

The whole code of error:

void trainer_es (string lang)
{

    ifstream in("dictionary_es.txt");
    if(!in)
    {
        cout<<"ERROR"<<endl;
        }

    string line;
    int right=0;
    int wrong=0;
    vector<string> english, spanish;
    bool is_english = true; 
    while(in.eof()==0)  
        { 
            getline(in,line);
            if(is_english   
            {
                english.push_back(line);
            }
                else 
            {
            spanish.push_back(line);

            }
        is_english = !is_english;   
        }

    in.close();

    unsigned long v_rand;
    srand(unsigned (time(nullptr)));

    if (lang == "english")
    {
        for (unsigned long int i=0; i<deutsch.size()-1; i++)
        {

            v_rand = rand() % (english.size());
            cout<<"Translate the word: "<<english.at(v_rand)<<endl;
            cin>>line;

            if(line == spanish.at(v_rand))
            {
                cout<<"right!"<<endl;
                right++;
            }

            else 
            {
                cout<<"wrong"<<endl;
                cout<<"the correct word is: "<<spanish.at(v_rand)<<endl;
                wrong++;
            }

        } 
    }

Thanks for your help

rand() returns an int , which is signed. english.size() returns a size_t , which is unsigned. So, to compute the expression rand() % english.size() , the return value of rand() will need to be cast to an unsigned type.

This causes an implicit conversion from int to unsigned long , which is throwing this warning.

I'd strongly suggest looking into std::uniform_int_distribution , which you can specify a return type for. Here's a good example of how to use it.

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