我写了一个程序,一次读取一个单词,直到一个'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'时它不会终止。 但是如果我放'^ Z'它会终止但是constantans总是1而其他的总是0。
答案 0 :(得分:1)
问题是std::cin
默认忽略所有标签和空格。所以在你的代码中
if (isspace(ch)) //check if ch is a space
space = true;
永远不会将space
设置为true
。避免此问题的一种方法是使用std::cin.get(ch)
代替std::cin>>ch
答案 1 :(得分:0)
希望这有助于你
#include<iostream>
#include<cstdlib>
#include<string>
int main()
{
char ch[50];
int consta, vowel, others;
consta = vowel = others = 0;
bool flag = false;
std::cout<<"Enter words (q to quit)\n";
while(1)
{
if(flag == true)
{
break;
}
gets(ch);
char* pch;
pch = strtok(ch," ");
if(strcmp("q",pch)==0)
{
break;
}
while (pch != NULL)
{
if(strcmp("q",pch)==0)
{
flag = true;
break;
}
if(isalpha(pch[0]))
{
if ((pch[0] == 'a' ||pch[0] == 'e' ||pch[0]== 'i' ||pch[0]== 'o' ||pch[0]== 'u') || (pch[0] == 'A' ||pch[0]== 'E' ||pch[0]== 'I' ||pch[0]== 'O' ||pch[0]== 'U'))
++vowel;
else
++consta;
}
else
++others;
pch = strtok (NULL, " ");
}
}
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";
std::cin.ignore();
return 0;
}
请参阅this以获取 strtok 。这将对所有单词进行计数,无论是用空格分隔还是用单独的行分隔。
答案 2 :(得分:0)
假设您要使用相同的代码结构,请在while循环中使用
while (cont && std::cin>> std::noskipws >>ch)
std :: noskipws:这会将cin流的行为更改为不忽略空格。它还在流的末尾添加了一个空格。小心末端空间。幸运的是,您的代码处理空格,因此您不会看到它的影响。
当您在代码中处理空格时,这将起作用。此外,默认情况下,cin的行为是忽略空格。
但是我认为你可以降低代码的复杂性,你可能不需要这个声明