简体   繁体   中英

How to fix “Not all control paths return a value” warning in c++?

[This isn't homework, I'm working through Bjarne Stroustrup's book Programming Principles and Practice Using C++ on my own]

I'm trying to make a simple program using a vector to convert a digit from 1 to 9 into its string equivalent, and vice-versa, using the same input loop, and my program seems to roughly work, but I get a warning "Not all control paths return a value". How can I fix this, and account for unexpected input?

Also, the while (true) condition seems messy. How can I adapt my code to give the user an option to manually exit the while loop?

#include "..\std_lib_facilities_revised.h"

vector<string> num_words = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

string print_num()
{
    int i = num_words.size();
    string s = " ";
    if (cin >> i) {
        if (i > -1 && i < num_words.size()) {
            return num_words[i];
        }
    }
    cin.clear();
    if (cin >> s) {
        for (int j = 0; j < num_words.size(); ++j) {
            if (s == num_words[j]) {
                return to_string(j);
            }
        }
    }
}

int main()
{
    while (true) {
        cout << "Enter a number: ";
        cout << print_num() << '\n';
    }
}

You just need to return some value at the end of the function in case all the if conditions ( if (s == num_words[j]) , if (i > -1 && i < num_words.size()) ) aren't met.

string print_num()
{
    int i = num_words.size();
    string s = " ";
    if (cin >> i) {
        if (i > -1 && i < num_words.size()) {
            return num_words[i];
        }
    }
    cin.clear();
    if (cin >> s) {
        for (int j = 0; j < num_words.size(); ++j) {
            if (s == num_words[j]) {
                return to_string(j);
            }
        }
    }
    return "";
}

如果两个cin >> s返回false ,则不会cin >> s任何return语句。

string print_num()
{
    int i = num_words.size();
    string s = " ";
    string error = "Enter valid input.";
if (cin >> i) {
    if (i > -1 && i < num_words.size()) {
        return num_words[i];
    }
}
cin.clear();
if (cin >> s) {
    for (int j = 0; j < num_words.size(); ++j) {
        if (s == num_words[j]) {
            return to_string(j);
        }
    }
}
// NO RETURN HERE
}

int main()
{
    while (true) {
        cout << "Enter a number: ";
        cout << print_num() << '\n';
        }
    }

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