提问者:小点点

打印时总是删除第一个单词


我对C++是完全陌生的,我试图做一个程序,它重复你输入的短语多少遍,但它不打印出第一个单词

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


}




}

共1个答案

匿名用户

将第一个单词读入短语时使用

std::cin >> phrase;

然后用下面一行的剩余单词覆盖变量

getline(std::cin,phrase );

您可以简单地删除

std::cin >> phrase;

从密码里。

下一个问题是

std::cin >> x;

只读取数字而不读取换行符。 必须忽略换行符

std::cin.ignore();

在此之前

getline(std::cin,phrase );