0

I am completely new to C++ and I was trying to make a program which repeated the phrase you entered how many times you want but it doesn't print out the first word.

#include <iostream>
using std::string;
using std::cin;

int main(){
    std::string phrase;
    int i;
    int x;
    std::cout << "Enter the number of times will be printed:\n";
    std::cin >> x;
    std::cout << "Now enter the phrase you want to be repeated:\n";
    std::cin >> phrase;
    getline(std::cin,phrase);

    while (i < x) {
        std::cout << phrase << "\n";
        i++;
    }
}
Adrian Mole
  • 30,672
  • 69
  • 32
  • 52
Nico
  • 1
  • 1
  • Related: [https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – drescherjm Jul 16 '20 at 15:07
  • it does not print the first word of the phrase or the first iteration of the phrase ? – Rodislav Moldovan Jul 16 '20 at 15:59

1 Answers1

3

You read the first word into phrase with

std::cin >> phrase;

and then you overwrite the variable with the remaining words of the line with

getline(std::cin,phrase );

You can simply remove

std::cin >> phrase;

from the code.

The next problem is that

std::cin >> x;

only reads the number and not the newline. You have to ignore the newline with

std::cin.ignore();

before

getline(std::cin,phrase );
Thomas Sablik
  • 15,040
  • 7
  • 26
  • 51