首页 > 解决方案 > 如何强制 C++ 只读取以 # 结尾的输入

问题描述

我试图在谷歌上找到答案,但没有找到任何东西,因此,任务是创建一个程序,该程序将仅在最后(“1234#”)读取输入(一串数字)并计算奇数和偶数。

我通过以下方式管理计数器:

char ch;
int odd_number,
    even_number;
odd_number=even_number = 0;
printf("To leave print % : ");
while((ch=getchar()) !='%')
{
    switch (ch)
    {
    case '1':
        odd_number++;
        break;
    case '2':
        even_number++;
        break;

但现在我不知道如何让它只读取最后带有 # 的数字字符串

标签: c++

解决方案


你需要做的是:

  • 循环执行所有操作,直到用户输入包含 '%'
  • 告知用户该怎么做
  • 从用户那里读取完整的输入行
  • 检查,如果那是一个非空字符串,由数字组成,最后有一个 #
  • 如果该行不符合请求的格式,则忽略它
  • 计算赔率。偶数的数量是字符串的其余部分(没有#)
  • 向用户显示结果

现在,在你的代码中翻译这个设计理念。

您必须开发自己的代码。

无论如何,我将提供一些示例代码,您可以尝试消化,并确保老师不相信这是您的解决方案。

请参见:

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

int main() {

    // Stay in program, until input string conatains a %
    for (std::string input{}; std::none_of(input.begin(), input.end(), [](const char c) {return c == '%'; });) {

        // Give instruction to the user
        std::cout << "Enter a number followed by a #  (a '%' in the string will end the program):\n-> ";

        // Get user input and check, if it is a valid numberdfgh
        if (std::getline(std::cin, input) and
            not input.empty() and
            input.back() == '#' and
            std::all_of(input.begin(), std::prev(input.end()), isdigit)) {

            // Count odd numbers
            size_t countOfOdds = std::count_if(input.begin(), std::prev(input.end()), [](const char c) {return c & 1; });

            // Calculate even numbers. That is the rest (without the #)
            size_t countOfEvens = input.size() - countOfOdds - 1;

            //Show result 0 user
            std::cout << "\nNumber contains " << countOfOdds << " odds and " << countOfEvens << " evens\n\n";
        }
    }
    return 0;
}

推荐阅读