c++ - 如何强制 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;
但现在我不知道如何让它只读取最后带有 # 的数字字符串
解决方案
你需要做的是:
- 循环执行所有操作,直到用户输入包含 '%'
- 告知用户该怎么做
- 从用户那里读取完整的输入行
- 检查,如果那是一个非空字符串,由数字组成,最后有一个 #
- 如果该行不符合请求的格式,则忽略它
- 计算赔率。偶数的数量是字符串的其余部分(没有#)
- 向用户显示结果
现在,在你的代码中翻译这个设计理念。
您必须开发自己的代码。
无论如何,我将提供一些示例代码,您可以尝试消化,并确保老师不相信这是您的解决方案。
请参见:
#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;
}
推荐阅读
- linux - 使用 Bash 从简单的 linux 脚本编辑变量
- go - 在节奏工作流的循环内调用相同的活动
- pytorch - Pytorch:将张量移动到 GPU 时,内存会发生什么变化?
- vba - Word VBA:扫描文档中的字符串,将其复制到列表中,然后移至下一个匹配项
- python - 如何在 Django 中转换字符串中的列表值?
- c++ - 对和花括号检查
- javascript - 尝试使用 Javascript 在 html 上制作时钟,但我的脚本无法正常工作。时钟实际上并没有运行
- excel - MS Access 2016 中 Excel 工作簿的无链接路径
- confluence - Comala/Confluence - 首次应用 Worfklow 时触发
- xml - 使用 xs:assert XSD 1.1 比较来自不同父级的两个 xml 元素