如何防止字符在 for 循环中打印两次?C++

How do I prevent character from being printed twice inside for loop? c++

本文关键字:两次 C++ 打印 字符 何防止 for 循环      更新时间:2023-10-16

这个问题看起来与其他问题相似(我已经检查过了。但是,提出的任何问题都没有我正在寻找的答案。

我正在使用C++编写一个程序来检查字符串中的字符是元音还是辅音,并使用计数器循环迭代字符串以产生结果。 isalpha() 位于一个名为 'isVowel' 的布尔函数中,它只做 2 件事。 1 它检查检查的值是否确实是合法的字母字符。 2 它检查字符是否是元音, 如果为 true,则返回 true 到 main。我需要指出为什么我的 cout 'is 元音' 在 for 循环"if (answer == true)"语句中的原始字符串下方打印两次的方向。

#include <iomanip>
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
bool isVowel(char word){
    if(isalpha(word)){
        if(word == 'a' || word == 'A')
        {
            return true;
        }   
    }
    return false;
}
int main ()
{   
    //Variables
    string choice;
    bool answer;
    //program starts here
    cout << setw(50) << "Vowels and Consonants" << endl;
    cout << "Please enter a word: ";
    cin >> choice;
    //while loop gathering each letter of the word to test for vowels/consonants
    /*while((unsigned)index < choice.length())*/
    for (int index = 0;(unsigned) index < choice.length();){
        char letter = choice[index];
        answer = isVowel(choice[index]);
        cout << letter <<  endl;
        if(answer != false){
            cout << letter << " is a vowel" << endl;    
        }
        index++;
    }
    return 0;   
}

您应该使用如下表达式更改第 36-40 行: cout << letter << ((answer != false) ? " is a voweln" : "n");