从数组中提取元音并将nd打印存储在另一个数组中

时间:2017-09-30 19:19:17

标签: c++ arrays

  

使用for循环编写程序,该循环存储来自Z-A的字母。仅从此数组中提取元音并将其存储到另一个数组元音中。现在使用来自元音数组的for循环显示这些元音。

我的输出无法正常工作。如果我写的名字没有像abdulhananhamid这样的空格,那么它就会起作用并显示a u a a 我不知道如何在for循环中使用cin

#include<iostream>
#include<conio.h>
using namespace std;

int vowel (char x);

int main()
{   
char size=100;
char x[size];
char A[5];
int n,i,;
cout<<"Enter any string\n";
cin>>x;

 for (i = 0, n = 0; i<size; i++)

    if (vowel(x[i]))
        A[n++] = x[i];

 for (n = 0;n<5;n++)
    cout << A[n] << " ";  

getch();
return 0;

 }
 int vowel(char x)   
{

 if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
 return 1;
else
 return 0;
 }

1 个答案:

答案 0 :(得分:0)

这对于使用bPtr[0]std::string来说是一个很好的作业。

std::getline

如果必须使用字符数组,则应检查溢出:

std::string user_text;
std::cout << "Enter a string: ";
while (std::getline(std::cin, user_text)
{
  const size_t length = user_text.length();
  std::string vowels;
  for (size_t i = 0; i < length; ++i)
  {
    const char c = user_text[i];
    if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u'))
    {
       vowels += c;
    }
  }
  std::cout << "Vowels found: " << vowels << "\n";
  std::cout << "\nEnter a string: ";
}

检查元音的功能可能如下所示:

unsigned int MAXIMUM_CHARACTERS = 128;
char user_text[MAXIMUM_CHARACTERS];
char vowels_found[MAXIMUM_CHARACTERS];
std::cout << "Enter a string: ";
while (std::cin.getline(&user_text[0], MAXIMUM_CHARACTERS))
{
  unsigned int vowel_index = 0U;
  const size_t length = strlen(user_text);
  for (size_t i = 0; i < length; ++i)
  {
    const char c = user_text[i];
    if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u'))
    {
       vowels_found[vowel_index++] = c;
    }
  }
  vowels_found[vowel_index] = '\0';
  std::cout << "Vowels found: " << vowels_found << "\n";
  std::cout << "\nEnter a string: ";
}