操纵字符串成1个字符
Manipulating string into taking in 1 character
我知道我的方法可能有点尴尬,我正在尝试验证菜单的输入,以便输入1-6之间的数字,而没有其他任何东西。我有工作代码,在其中将输入作为字符串进行输入,然后将其更改为INT以便在开关情况下使用它,但是我知道我可以使其更有效地工作。有什么想法吗?
void menu(double pi, char ssTwo) //menu for choosing a shape
{
string choice;
cout << "Welcome to the shape calculator!nnPlease select what you wish to calculate:nn1 - Area of a Circlenn2 - Circumference of a Circlenn3 - Area of a Rectanglenn4 - Area of a Trianglenn5 - Volume of a Cuboidnn6 - Exit the programnn ";
cin >> choice;
while (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5" && choice != "6")
{
cout << "Invalid input, please enter a number of 1-6nn";
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
int choiceInt = atoi(choice.c_str());
system("CLS");
switch (choiceInt) //switch case for each shape
{
case 1:
circleArea(pi, ssTwo);
break;
case 2:
circleCircum(pi, ssTwo);
break;
case 3:
rectanArea(ssTwo);
break;
case 4:
triangArea(ssTwo);
break;
case 5:
cubVol();
break;
case 6:
exitSystem();
break;
default:
cout << "Invalid input, please enter a number of 1-5nn";
menu(pi, ssTwo);
break;
}
}
将char视为ASCII值;检查http://rextester.com/xkmj90988
#define ONE 49
#define TWO 50
int main()
{
char val = '1';
switch (val)
{
case ONE:
{
std::cout << "1 was Selected";
break;
}
case TWO :
{
std::cout << "2 was Selected";
break;
}
default:
std::cout << "Invalid input, please enter a number of 1-5nn";
break;
}
}
更新#1
检查:http://rextester.com/wwum1166
,如果您将CIN的值读取到字符中而不是字符串,它只会采用第一个字符;因此,如果用户按" 1ASDFAD",您将只有1个字符,并且将使用1个;如果按下" asdfasdf",它将读取" a",并显示无效的输入;
int main()
{
char val;
std::cout << "Enter a number: ";
std::cin >> val;
std::cout << val << "n";
switch (val)
{
case '1':
{
std::cout << "1 was Selected";
break;
}
case '2':
{
std::cout << "2 was Selected";
break;
}
default:
std::cout << "Invalid input, please enter a number of 1-5nn";
break;
}
}
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 将stl字符串缩小到小于15个字符的容量
- 带有多个字符分隔符的正则表达式
- 查找字符在两个索引之间出现的次数
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 如何删除字符串中的前 2 个字符(如果它有"-")
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 注册表正在设置 1 个字符
- 使用类 ?C++ 和 SFML 以及标题中的 15 个字符
- 如何忽略第一个字符输入后的所有内容
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- std::stoi 只转换前几个字符
- 仅读取文件末尾的最后 3 个字符,并将其另存为 int
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- C++字符数组不接受超过 4 个字符的输入
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 增量生成 - 错误:字符串的第一个字符应'0'或'1'
- 在 c++ 的 10x10 数组中生成特定数量的多个随机字符
- 函数返回两个字符串的第一个常用字符