Home > OS >  How to solve this strange bug? (c )
How to solve this strange bug? (c )

Time:07-16

#include <iostream>
#include <vector>
int main()
{ 
  std::string human = "";
  std::vector <char> translate;
  std::cout << "Enter English words or sentences to tranlate it into Whale's language.\n";
  std::cin >> human;
  for (int a = 0; a < human.size(); a  ){
      if (human[a] == 'a' || human[a] == 'i' || human[a] == 'o' || human[a] == '.' || human[a] == ',' || human[a] == '?' || human[a] == '!' || human[a] == ' '
       || human[a] == 'A' || human[a] == 'I' || human[a] == 'O' || human[a] == '-'){
      translate.push_back(human[a]);}
      if (human[a] == 'e' || human[a] == 'u' || human[a] == 'E' || human[a] == 'U'){
          translate.push_back(human[a]);
          translate.push_back(human[a]);}}
  for (int b = 0; b < translate.size(); b  ){
      std::cout << translate[b];}
    }

The program above is about to translate words into other words. There are two rules for the translation, 1. keep all the 'a', 'i', 'o'. 2. keep all the 'e' and 'u' and then double it.

E.g. if I type "Hello world.",it should output "eeo o."

But the question is, my code does not work like that, it just output "eeo", which is odd I think. Can someone explain why?

CodePudding user response:

Reading from an ifstream into a string will break on whitespaces, hence cin >> human only reads what's effectively the first word.

Change this:

std::cin >> human;

To this:

std::getline(cin, human);

While we're here, let's cleanup the code:

#include <iostream>
#include <unordered_set>
#include <string>

int main()
{ 
  std::string human;
  std::string translate;

  std::unordered_set<char> keepers = {'a','i', 'o', 'A','I','O'};
  std::unordered_set<char> doublers = {'e', 'u', 'E', 'U'};

  std::cout << "Enter English words or sentences to translate it into Whale's language.\n";

  std::getline(cin, human);

  for (char c : human) {
      if (keepers.find(c) != keepers.end() || ::ispunct(c) || ::isspace(c)) {
          translate  = c;
      }
      else if (doublers.find(c) != doublers.end()) {
          translate  = c;
          translate  = c;
      }
  }
  std::cout << translate << std::endl;
}
  •  Tags:  
  • c
  • Related