Nico
Nico

Reputation: 1

First Word always gets deleted when printed

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++;
    }
}

Upvotes: 0

Views: 169

Answers (1)

Thomas Sablik
Thomas Sablik

Reputation: 16454

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 );

Upvotes: 3

Related Questions