要求在循环中写一个句子来计算元音,即使循环进行也不会再问

Asking to write a sentence in a loop to count vowels, won't ask again even when the loop goes on

本文关键字:循环 句子 一个 计算      更新时间:2023-10-16

标题可能有点令人困惑,我尽量具体

嗨,这里的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++知之甚少(几天前才开始(,任何帮助都将不胜感激!

首先,inb_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);