Whale Talk program not iterating through user input correctly

In the whale challenge for C++ I am assigning user input to the string variable.

This block of code works as intended when I use a hard coded string variable. It produces the expected result of uueeieeauuee.

#include <iostream>
#include <vector>

//Iterate through the string and if element in index is a vowel, push that element into a vector.
int main () {
  std::string whale = "turpentine and turtles.\n";
  std::vector<char> vowels;
  for (int i = 0; i < whale.size(); i++) {
    if (whale[i] == 'a' || whale[i] == 'i' || whale[i] == 'o') {
      vowels.push_back(whale[i]);
      }
    else if (whale[i] == 'e' || whale[i] == 'u') {
      for (int x = 0; x < 2; x++){
        vowels.push_back(whale[i]);
        }
      }
    }
  for (int i = 0; i < vowels.size(); i++) {
    std::cout << vowels[i];
    }
  std::cout << "\n";
  return 0;
}
However when I replace the hard coded string with the following to allow user input:
#include <iostream>
#include <vector>

//Iterate through the string and if element in index is a vowel, push that element into a vector.
int main () {
  std::string whale;
  std::cout << "Type in a sentence to translate to Whalenese.\n";
  std::cin >> whale;
  std::vector<char> vowels;
  for (int i = 0; i < whale.size(); i++) {
    if (whale[i] == 'a' || whale[i] == 'i' || whale[i] == 'o') {
      vowels.push_back(whale[i]);
      }
    else if (whale[i] == 'e' || whale[i] == 'u') {
      for (int x = 0; x < 2; x++){
        vowels.push_back(whale[i]);
        }
      }
    }
  for (int i = 0; i < vowels.size(); i++) {
    std::cout << vowels[i];
    }
  std::cout << "\n";
  return 0;
}

When the input is turpentine and turtles, the output received is uueeiee

Can someone explain why I am not getting the expected output please?

When you enter "turpentine and turtles" as the input, then std::cin will stop once it encounters the space and consequently, whale will be assigned the string "turpentine" only.

Have a look at the section titled "cin and strings" in https://cplusplus.com/doc/tutorial/basic_io/:

However, cin extraction always considers spaces (whitespaces, tabs, new-line…) as terminating the value being extracted, and thus extracting a string means to always extract a single word, not a phrase or an entire sentence.

The above link proposes you use getline instead.

// You wrote:
std::cin >> whale;

// Change it to:
std::getline(std::cin, whale);

Some other reading material:

Thank you for the helpful and interesting insight. I appreciate your answer :grin:

1 Like