[英]Using cin.get() doesn't seem to read the character I'm expecting. What's wrong?
so I'm working on this program to perform a menu of basic tasks, one of which is to tell whether a character input by the user is uppercase, lowercase, or not a letter. 因此,我正在使用该程序执行基本任务菜单,其中一项任务是告诉用户输入的字符是大写,小写还是不是字母。
#include <iostream>
using namespace std;
int main () {
int mi;
cout << "1) Area of Circle" << endl;
cout << "2) Character Detection" << endl;
cout << "3) Capitalization 1-3-5" << endl;
cout << "4) Binomial Roots" << endl;
cout << "0) Quit" << endl;
cin >> mi;
switch (mi) {
case 2:
{
char c;
cout << "input a character: ";
cin.get(c);
cin.ignore(); /////// unsure if using this properly
if ('a' <= c && c <= 'z') {cout << "c is lower case" << endl;}
else if ('A' <= c && c <= 'Z') {cout << "C IS UPPER CASE" << endl;}
else { cout << "C is not a letter" << endl;}
}
break;
}
return 0;
}
after selecting 2 and inputting a letter (or any other character) the output is always "C is not a letter." 选择2并输入字母 (或其他任何字符)后,输出始终为“ C不是字母”。
What confuses me is that if I take what's in case 2 and put it in a separate program, ie 令我感到困惑的是,如果我将情况2中的内容放入单独的程序中,即
using namespace std;
int main () {
char c;
cout << "input a character: ";
cin.get(c);
if ('a' <= c && 'z' >= c) {cout << "c is lower case" << endl;}
else if ('A' <= c && c <= 'z') {cout << "C IS UPPER CASE" << endl;}
else { cout << "C is not a letter" << endl;}
return 0;
}
It works exactly how it's supposed to, and I don't even need cin.ignore(), because for some reason it only skips the user input part when it's in the switch statement. 它完全按照预期的方式运行,我什至不需要cin.ignore(),因为某些原因,它仅在switch语句中时才跳过用户输入部分。 What am I missing here? 我在这里想念什么?
I would recommend you to use cin>>
instead of cin.get()
as the cin.get()
after every initialization is there to "grab" the newline character that gets put in the stream every time you press enter. 我建议您在每次初始化之后使用cin>>
而不是cin.get()
作为cin.get()
来“抓住”每次按Enter时流中放置的换行符。
#include <iostream>
using namespace std;
int main () {
int mi;
cout << "1) Area of Circle" << endl;
cout << "2) Character Detection" << endl;
cout << "3) Capitalization 1-3-5" << endl;
cout << "4) Binomial Roots" << endl;
cout << "0) Quit" << endl;
cin >> mi;
switch (mi) {
case 2:
{
char c;
cout << "input a character: ";
cin>>c;
cin.ignore(); /////// unsure if using this properly
if ('a' <= c && c <= 'z') {cout << "c is lower case" << endl;}
else if ('A' <= c && c <= 'Z') {cout << "C IS UPPER CASE" << endl;}
else { cout << "C is not a letter" << endl;}
}
break;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.