什么时候和为什么我需要在C ++中使用cin.ignore()? [英] When and why do I need to use cin.ignore() in C++?

查看:644
本文介绍了什么时候和为什么我需要在C ++中使用cin.ignore()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中写了一个非常基本的程序,要求用户输入一个数字,然后输入一个字符串。令我惊讶的是,当运行程序时,它从来没有停止要求的字符串。它只是跳过了它。在StackOverflow上做一些阅读后,我发现我需要添加一行说:

I wrote a very basic program in C++ which asked the user to input a number and then a string. To my surprise, when running the program it never stopped to ask for the string. It just skipped over it. After doing some reading on StackOverflow, I found out that I needed to add a line that said:

cin.ignore(256, '\n');

。添加这一点固定的问题,并使程序工作。我的问题是C ++为什么需要这个 cin.ignore()行,我怎么预测什么时候需要使用 cin.ignore()

before the line that gets the string input. Adding that fixed the problem and made the program work. My question is why does C++ need this cin.ignore() line and how can I predict when I will need to use cin.ignore()?

这是我写的程序:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    double num;
    string mystr;

    cout << "Please enter a number: " << "\n";
    cin >> num;
    cout << "Your number is: " << num << "\n";
    cin.ignore(256, '\n'); // Why do I need this line?
    cout << "Please enter your name: \n";
    getline (cin, mystr);
    cout << "So your name is " << mystr << "?\n";
    cout << "Have a nice day. \n";

}


推荐答案

忽略

它不会抛弃你不需要的东西,它忽略了你调用它时指定的字符数量,直到您指定为断点的字符。

It doesn't "throw away" something you don't need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint.

它适用于输入和输出缓冲区。

It works with both input and output buffers.

基本上,对于 std :: cin 语句,您可以在执行 getline 调用,因为当用户使用 std :: cin 输入内容时,他们按Enter键并输入'\\\
'
char进入 cin 缓冲区。然后,如果你使用 getline ,它得到newline的char而不是你想要的字符串。所以你做一个 std :: cin.ignore(1000,'\\\
')
,并应该清除缓冲区,直到你想要的字符串。 (1000放在那里,在指定的断点之前跳过特定数量的字符,在这种情况下是\\\
换行符。)

Essentially, for std::cin statements you use ignore before you do a getline call, because when a user inputs something with std::cin, they hit enter and a '\n' char gets into the cin buffer. Then if you use getline, it gets the newline char instead of the string you want. So you do a std::cin.ignore(1000,'\n') and that should clear the buffer up to the string that you want. (The 1000 is put there to skip over a specific amount of chars before the specified break point, in this case, the \n newline character.)

这篇关于什么时候和为什么我需要在C ++中使用cin.ignore()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆