要求在循环中写一个句子来计算元音,即使循环进行也不会再问
Asking to write a sentence in a loop to count vowels, won't ask again even when the loop goes on
标题可能有点令人困惑,我尽量具体
嗨,这里的c++初学者,试图让工作成为一个简单的程序,告诉我一个句子包含多少元音。这里的问题是,循环并没有要求我在第一次迭代后继续写一个应该写的句子。
所以基本上这是我的代码:
#include <iostream>
using namespace std;
int main(){
int i, nb_vowels, cont=1;
char sentence[100];
while(cont!=0){
cout << "Enter a sentence : ";
while ((sentence[i] = getchar()) != 'n') {
i++;
if(sentence[i]=='a' || sentence[i]=='e'|| sentence[i]=='i' || sentence[i]=='o' || sentence[i]=='u'){
nb_vowels++;
}
}
sentence[i] = ' ';
cout << "Number of vowels : " << nb_vowels <<endl;
cout << "1 to continue or 0 to stop : ";
cin >> cont;
}
}
下面是我执行它时的一个例子:
Enter a sentence : hello i am learning c++
Number of vowels : 1 //that part is still not working btw, but i want to know how to fix the loop problem first
1 to continue or 0 to stop : 1
Enter a sentence : Number of vowels : 1 //i cant write anything here, it just pops like that
1 to continue or 0 to stop :
以下是它应该如何进行:
Enter a sentence : hello i am learning c++
Number of vowels : 6
1 to continue or 0 to stop : 1
Enter a sentence : wooo it works
Number of vowels : 1
1 to continue or 0 to stop : 0
我现在有点迷路了,因为我对C++知之甚少(几天前才开始(,任何帮助都将不胜感激!
首先,i
和nb_vowels
没有初始化为任何内容,正确初始化为:int nb_vowels = 0, i = 0;
其次,为什么不使用cin.getline(sentence, 100);
输入句子,为什么循环自己来完成这项任务?
如果你使用cin.getline
,你必须在输入cin >> cont;
后添加一个cin.ignore();
以下是您可以用来执行此任务的代码:
int cont = 1;
int nb_vowels = 0;
char sentence[100];
while (cont != 0){
cout << "Enter a sentence: ";
cin.getline(sentence, 100);
int sentenceSize = strlen(sentence);
for (int i = 0; i < sentenceSize; i++){
if (sentence[i] == 'a' || sentence[i] == 'e'|| sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
nb_vowels++;
}
cout << "No. of Vowels: " << nb_vowels << endl;
cout << "1 to continue or 0 to stop : ";
cin >> cont;
cin.ignore();
}
更好的是,应该使用std::string
而不是char
数组。阅读string
,这很简单,如果你对此有任何问题,首先搜索该问题,然后找到一些真正的问题。
在cout<<"no of vowels"
之前使用fflush(stdin);
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 在for循环外显示句子数组
- 要求在循环中写一个句子来计算元音,即使循环进行也不会再问