1

I'm taking Codecademy's learn C++ course and one of the projects is "whale translator" that takes in a text and translates into its whale equivalent.

There are a few simple rules for translating text to whale language:

  • There are no consonants. Only vowels excluding the letter y.
  • The u‘s and e‘s are extra long, so we must double them.

The issue is that, when you enter a sentence, for example, it stops translating after it comes across whitespace and only translates the first word, but if I declare the string I want to translate instead of asking for an input from the user, it works fine.

Here's my code:


#include <iostream>
#include <vector>
#include <string>

int main(){
  std::string input;
  std::cout << "Enter the text to translate:\n";
  std::cin >> input;

  std::vector<char> vowels = {'a', 'e', 'i', 'o','u'};
  vowels.push_back('A');
  vowels.push_back('E');
  vowels.push_back('I');
  vowels.push_back('O');
  vowels.push_back('U');
  std::vector<char> punctuation = {'.', ',', '?', '!',':', ';', '(', ')'};
  std::vector<char> result;

  for(int i = 0; i < input.size(); i++){
    //nested loop for vowels
    for(int m = 0; m < vowels.size(); m++){
      //compare input string to vowels vector using if statement
      if(input[i] == vowels[m]){
        result.push_back(input[i]);
      }
    }
    //doubling e's and u's
    if(input[i] == 'e' || input[i] == 'E' || input[i] == 'u' || input[i] == 'U'){
      result.push_back(input[i]);
    }
  }
  //punctuation
  for (int i = 0; i < input.size(); i++){
   for (int k = 0; k < punctuation.size(); k++){
    if (input[i] == punctuation[k]){
      result.push_back(input[i]);
      }
}
}
  for(int j = 0; j < result.size(); j++){
    std::cout << result[j];
  }
  std::cout << "\n";
}
  • 1
    `std::cin >> input;` will grab all the characters it can until it hits any whitespace. Did you want `std::getline(std::cin, input)`? – scohe001 Oct 01 '20 at 13:48
  • Does this answer your question? [std::cin input with spaces?](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) – scohe001 Oct 01 '20 at 13:49
  • A good first step when the output is surprising is to verify that the input is what you're assuming it to be: `std::cout << input;`. – molbdnilo Oct 01 '20 at 13:51
  • Note that if this is online task, then usually there is no output inviting for entering data. You can print only things which are clearly stated in the problem description, so `"Enter the text to translate:\n"` can lead to invalid answer. – Marek R Oct 01 '20 at 13:53
  • @MarekR There was no output, I modified it on my own and wrote it on the local ide. –  Oct 01 '20 at 14:01

1 Answers1

3

That's because >> stops reading as soon as it finds white space. If you want to read a whole line of text use getline.

getline(std::cin, input);
john
  • 85,011
  • 4
  • 57
  • 81