【问题标题】:Creating " if not an integer" if statement condition (C++)创建“如果不是整数”if 语句条件 (C++)
【发布时间】:2020-05-24 05:07:31
【问题描述】:

处理用户以某种格式输入一些数据(例如“Ernest Hemingway, 9”)的作业,然后将这些信息放入表格中。

我必须考虑用户输入中的错误。不放逗号,放太多逗号,检查“,”后面的数据是否为有效整数。

例如。 欧内斯特·海明威 9

错误:字符串中没有逗号。

欧内斯特,海明威,9

错误:输入的逗号过多。

欧内斯特·海明威,九岁(输入我遇到问题)

错误:逗号后面没有整数。

欧内斯特·海明威,9 岁

数据字符串:欧内斯特·海明威 数据整数:9

下面是我当前的代码

    int commaCount = 0; // keeps track of commas in users input
    int currentIndex = 0; // creating variable to create elements in the vectors

    do
    {
        cout << "Enter a data point (-1 to stop input) :" << endl;
        getline(cin, userInput);

        if (userInput == "-1") { break; } // meant to break out of loop if the user inputs "-1" on their first attempt

        for (int i = 0; i < userInput.length(); i++) {
            if (userInput.at(i) == ',') {
                commaCount++;
            }
        }

        if (commaCount == 0) {
            cout << "Error: No comma in string." << endl;
        }

        else if (commaCount > 1) {
            cout << "Error: Too many commas in input." << endl;
        }

        //else if ( second half of string != a POSITIVE int) "If entry after the comma is not an integer"

        else {
        breakPoint = userInput.find(',');

        listOfAuthors.push_back(userInput.substr(0, breakPoint));
        novelsPerAuthor.push_back(stoi(userInput.substr(breakPoint + 1, userInput.length() - breakPoint + 1)));


        cout << "Data string: " << listOfAuthors.at(currentIndex) << endl;
        cout << "Data integer: " << novelsPerAuthor.at(currentIndex) << endl;
        currentIndex++;

        }

        commaCount = 0; // resets comma count between entries

        cout << " " << endl;
    } while (userInput != "-1"); //exits user input loop if "-1" is inputed

下面是我如何分隔字符串并将后半部分转换为 int 的代码,如果它有助于为上面的代码提供上下文。

breakPoint = userInput.find(',');

        listOfAuthors.push_back(userInput.substr(0, breakPoint));
        novelsPerAuthor.push_back(stoi(userInput.substr(breakPoint + 1, userInput.length() - breakPoint + 1)));

如果 userInput.substr(breakPoint + 1, userInput.length() - breakPoint + 1)) 不等于正整数,有没有办法编写一个条件来说明某些内容,程序将打印“错误: 逗号后面不跟整数。"

【问题讨论】:

  • 最简单的方法是编写一个函数 isAPositiveInteger,然后从您的 if 语句 if (!isAPositiveInteger(userInput.substr(breakPoint + 1, userInput.length() - breakPoint + 1))) { "Error: Comma not followed by an integer." } 中调用该函数。解决任何复杂编程任务的方法是将其分解为多个部分并编写函数来解决各个部分。如果第二个参数被省略,您可以通过实现 substr 默认为字符串的其余部分来更简单地实现这一点。所以userInput.substr(breakPoint + 1) 就是你所需要的。
  • 顺便说一句,整个任务会变得相当容易,如果您使用 C++ 正则表达式库,代码会变得更加健壮。

标签: c++ string if-statement do-while


【解决方案1】:

您需要使用从 std::string 到整数的转换器。在 C++ 中有几种方法可以做到这一点,但我认为使用 stoi 函数将涵盖所有情况(请注意,如果您尝试转换不是整数的字符串,stoi 会引发异常)

这是一个如何实现的小例子

#include <iostream>
#include <string>

std::string /* error string */ SplitLine(const std::string& inLine, std::string& outString, int& outNumber)
{
    const std::string separator = ",";
    auto pos = inLine.find(separator);
    auto pos2 = inLine.rfind(separator);

    if (pos == std::string::npos) {
        return "No comma in string.";
    }

    if (pos != pos2 && pos2 != std::string::npos) {
        return "Too many commas in input.";
    }

    outString = inLine.substr(0, pos);
    std::string remain_part = inLine.substr(pos+1);
    try {
        outNumber = stoi(remain_part);
    }
    catch (...) {
        return "Comma not followed by an integer.";
    }

    return "";
}

void ProcessLine(const std::string& inLine)
{
    std::string result;
    int num = 0;
    auto error = SplitLine(inLine, result, num);

    if (!error.empty()) {
        std::cout << "Error: " << error << std::endl;
    }
    else {
        std::cout << "Data string: " << result << " Data integer: " << num << std::endl;
    }

}

int main()
{
    ProcessLine("Ernest Hemingway 9");
    ProcessLine("Ernest, Hemingway, 9");
    ProcessLine("Ernest Hemingway, nine");
    ProcessLine("Ernest Hemingway, 9");

    return 0;
}

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2023-02-03
    • 1970-01-01
    • 2011-05-10
    • 2014-11-23
    • 2019-04-12
    • 1970-01-01
    • 2020-10-23
    • 2016-01-03
    相关资源
    最近更新 更多