简体   繁体   English

如何在c ++中修复“并非所有控制路径返回值”警告?

[英]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] [这不是家庭作业,我正在通过Bjarne Stroustrup的书“我自己使用C ++编写原理和实践”一书]

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". 我正在尝试使用向量将一个简单的程序转换为1到9的数字到它的字符串等效,反之亦然,使用相同的输入循环,我的程序似乎大致工作,但我得到一个警告“并非所有控制路径都返回值“。 How can I fix this, and account for unexpected input? 我该如何解决这个问题,并考虑到意外的输入?

Also, the while (true) condition seems messy. 而且, while (true)条件似乎很混乱。 How can I adapt my code to give the user an option to manually exit the while loop? 如何调整我的代码以便为用户提供手动退出while循环的选项?

#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. 你只需要在函数结尾处返回一些值,以防所有if条件( if (s == num_words[j])if (i > -1 && i < num_words.size()) )不是满足。

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';
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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