cin.getline() 不适用于 switch 语句
cin.getline() isn't working with switch statement
我一直在尝试为课程上的程序工作一个字符串,直接回到菜单。ex)输入1中的结果是:输入字符串:01。添加数字,但忽略了任何不是数字的东西。如果我使用常规的CIN语句,代码将很好地执行。我不明白为什么这样做。有人可以帮忙吗?
#include <iostream>
#include <cctype>
using namespace std;
void firstChoice(char []);
int main()
{
int choice;
int answer;
const int SIZE = 100;
char line[SIZE];
do
{
cout << "1. Adds numbers but ignores anything thats not a number." << endl;
cout << "2. Count the number of consonants in a string." << endl;
cout << "3. Counts the vowels in a string." << endl;
cout << "4. Counts whitespace characters in a string." << endl;
cout << "Enter a number to access that program or 0 to end it: ";
cin >> choice;
switch(choice)
{
case 1:
cout << "nEnter a string: ";
cin.getline(line, SIZE);
firstChoice(line);
break;
case 2:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
case 3:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
case 4:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
}
}
while(choice != 0);
return 0;
}
void firstChoice(char line[])
{
int size2 = 0;
int sum = 0;
while(line[size2] != ' ')
{
if(isalpha(line[size2]))
{
line[size2] = 0;
}
sum += line[size2];
size2++;
}
cout << sum;
}
此语句之后
cin >> choice;
使用
#include <limits>
//...
cin >> choice;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );
相关文章:
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 适用于 WebView2 旧版本的示例应用程序
- 在 NVIDIA GEFORCE GTX 1050 上下载适用于 Windows 10 的 openCL 1.2
- __attribute__(优化(0))) 是否适用于"recursively"?
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- 使用一个参数的模板函数时出错(适用于 2)
- 使用 适用于 Android 和 iOS 的 tf-lite C++ API
- 为什么这适用于 G++ 而不是 CLANG?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 适用于 Linux 的 c++ 上的代理脚本
- 为什么我的 SFINAE 表达式不再适用于 GCC 8.2?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 有没有适用于Windows.lib文件的GNU二进制文件描述符(BFD)
- 模板函数仅适用于VS
- 如何在cmake中包含适用于g++或viceversa的库
- 适用于win32、linux、mac的POSIX C包装器
- WinDBG适用于从Visual Studio 2015保存的转储,但不适用于任务管理器。显示异常代码"not found"
- 从uint8_t到NPY_UINT16 PyArray_SimpleNewFromData.适用于Linux,但不适用于