获取线 CIN 忽略输入中的第一个数字

getline cin ignoring first number from input

本文关键字:第一个 数字 输入 CIN 获取      更新时间:2023-10-16

我现在正在学习C++,我目前正在尝试使用 cin 和 getline 获取输入。但是,getline以某种方式忽略了输入中的数字。我尝试放置cin.clear()和cin.ignore(),但问题仍然存在。我做错了什么吗?

这是我的代码:

string test;
int main()
{
    std::cout << "Please enter a date: ";
    std::cin >> test;
    std::getline(std::cin, test);
    cout << test << endl;
}

这是输出:

Please enter a date: 1 January 2015
 January 2015
Press any key to continue . . .

除非你想读一些东西,否则不要使用std::cin

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
int main()
{
    string test; // Don't use global variable unless it is necessary.
    std::cout << "Please enter a date: " << std::flush;
    // std::cin >> test; // remove this harmful line
    std::getline(std::cin, test);
    cout << test << endl;
    cout << "Press any key to continue . . ." << endl;
    return 0;
}

>getline不会追加。您正在读入字符串,直到它到达空格,然后用该行的其余部分覆盖它。

std::cin >> test; //test == "1"
std::getline(std::cin, test); //test == " January 2015"