到目前为止,当你输入f时没有任何反应它只有在输入0时才有效但是我想要它,所以当你按下f你得到这个ab abc abcd abcde abcdef
#include <iostream>
using namespace std;
int main()
{
int f = 0;
int z;
cout << "";
while(cin >> f)
{
if(f == 0)
{
cout << "ABCDEF\nABCDE\nABCD\nABC\nAB\nA";
break;
}
}
}
答案 0 :(得分:1)
变量f
是一个int。按键&#39; f&#39;时,cin
istream会尝试将int
设置为&#39; f&#39;,这不是数字,所以从字符到数字的转换失败。
该失败设置了cin
中的坏位,它突破了while循环。
答案 1 :(得分:0)
将输入读入char
很容易:std::cin >> c
char c
会这样做。
有趣的是编写便携式方式将字母打印到某个字符。这是一种方式:
// Prints up to and including 'c'.
// Outputs the alphabet if 'c' is not a lower case letter.
void print(char c)
{
static const char s[] = "abcdefghijklmnopqrstuvwxyz";
for (std::size_t i = 0; s[i]; ++i){
std::cout << s[i];
if (s[i] == c){
std::cout << '\n';
return;
}
}
}
答案 2 :(得分:0)
如果输入f,则会导致错误,因为它需要一个整数。您可以将char转换为整数。如果要在输入f时输入结果,则必须选择:
1
char input;
std:cin >> input;
if((int)input == 102){
.....
2
char input;
std:cin >> input;
if(input == 'f'){
.....
编辑: 如果你想按降序打印字母表,迈克尔罗伊有一个很好的解决方案,但在订购
if....
for(char i = input; i >= 'a'; --i)
cout << i - 32; //the 32 is for converting the lower case char into upper case
cout << '\n';
所以总的来说它看起来像这样:
char input;
std:cin >> input;
if('a' < input < 'z'){
for(char i = input; i >= 'a'; --i)
cout << i - 32;
cout << '\n';
}else{
cout << "Not a valid input";
}
System("Pause");//so the console doesn't close automatically
答案 3 :(得分:0)
这是让你的程序做你想做的一种方法:
#include <iostream>
using namespace std;
int main()
{
char c = 0; // we want chars, not integers.
int z;
cout << "";
while (cin >> c)
{
if ('a' <= c && c <= 'z') // test for the range we want
{
// print all glyphs from a to 'c'
for (char i = 'a'; i <= c; ++i)
cout << i;
cout << '\n';
break;
}
}
}