我编写了一个程序,它一次读取输入一个单词,直到输入一个单独的“q”。然后程序报告以元音开头的单词数,以辅音开头的单词数,以及不符合这两个类别的数。
#include <iostream>
#include <cstdlib>
int main()
{
char ch;
bool cont = true; //for controlling the loop
bool space = false; //see if there is a space in the input
int i = 0; //checking if the input is the first word
int consta, vowel, others;
consta = vowel = others = 0;
std::cout<<"Enter words (q to quit)\n";
while (cont && std::cin>>ch) //continue while cont is true and the input succeded
{
if (i == 0) //check if this is the first word
{
if (isalpha(ch))
if ((ch == 'a' ||ch == 'e' ||ch== 'i' ||ch== 'o' ||ch== 'u') || (ch == 'A' ||ch== 'E' ||ch== 'I' ||ch== 'O' ||ch== 'U'))
++vowel;
else
++consta;
else
++others;
++i; //add 1 to i so this if statement wont run again
}
if (space == true) //check if the last input was a space
{
if (!isspace(ch)) //check if the current input is not a space
{
if (ch != 'q') //and ch is not 'q'
{
if (isalpha(ch))
if ((ch == 'a' ||ch == 'e' ||ch== 'i' ||ch== 'o' ||ch== 'u') || (ch == 'A' ||ch== 'E' ||ch== 'I' ||ch== 'O' ||ch== 'U'))
++vowel;
else
++consta;
else
++others;
space = false;
}
}
else
cont = false;
}
if (isspace(ch)) //check if ch is a space
space = true;
}
std::cout<<"\n"<<consta<<" words beginnig with constants\n";
std::cout<<vowel<<" words beginnig with vowels\n";
std::cout<<others<<" words beginning with others\n";
system("pause");
return 0;
}
但是当我输入空格和'q'时它不会终止。但是如果 i 输入 '^Z' 它确实会终止,但康铜始终为 1,其他始终为 0。