Home > OS >  How to get a full sentence from user input and run it through a for loop to then output on terminal
How to get a full sentence from user input and run it through a for loop to then output on terminal

Time:01-08

I'm practicing using vectors and arrays and seeing the difference between both. I accomplished this program using vectors and an array. So far I can get the program to do what I want it to do, that is until I include user input. The program will read the first word of the sentence but omit the rest. I did some research and have tried including cin.getline() before the first for loop, but that didn't work. I tried other getline methods like pre setting the value at zero but I end up getting lost with a bunch of errors, or it outputs only part of the sentence.

#include <iostream>
using namespace std;

int main() {

    string input = "turpentine and turtles";
    char vowels\[] ={ 'a', 'e', 'i','o', 'u' };

    for (int i=0; i < input.size(); i  ) {
        for (int j=0; j < 5; j  ) {
            if (input[i] == vowels[j]{
            cout << input[i]; }
        }
        if (input[i] == 'e') {
            cout << input[i];
        }
        if (input[i] == 'u') {
            cout << input[i];
        }
    }
}

CodePudding user response:

I solve your code to print vowels characters in the input sentence `

string input = "turpentine and turtles";
char vowels[] = {'a', 'e', 'i', 'o', 'u'};

for (int i = 0; i < input.size(); i  )
{
    for(int j=0;j<5;j  ){
        if(input[i] == vowels[j])
        {
            cout << input[i]<<" ";
        }
    }
}

`

CodePudding user response:

Welcome to StackOverflow. Use std::getline to read in the line provided by the user.

There are several build-breaking typos in your code, which I've fixed below.

Also, it's in your best interest to avoid using namespace std; - it's rarely worth the trouble it can cause.

Remember your includes for <string>, et al as well.

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

int main() {
    auto vowels = std::vector{ 'a', 'e', 'i', 'o', 'u' };
    auto input = std::string();
    //auto input = std::string("turpentine and turtles");

    std::getline(std::cin, input);

    for (int i = 0; i < input.size(); i  ) {
        if (vowels.contains(input[i])) {
            std::cout << input[i] << ' ';
        }
    }
}
  •  Tags:  
  • c
  • Related