为什么第一个get()在这段代码中不起作用? [英] Why does the first gets() not work in this code?

查看:73
本文介绍了为什么第一个get()在这段代码中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用dev c ++和code :: Blocks尝试了这个代码(在多个程序中)但是第一个gets()命令永远不会被执行,后面跟着cin>>





I have tried this code (in multiple programs) using dev c++ and code::Blocks but the first gets() command will never get executed when followed by a cin>>


#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    int i;
    char c[10], d[10];
    cout<<"Enter int ";
    cin>>i;
    cout<<"Enter string ";
    gets(c); // this is where things act all possessed
    cout<<"Enter 2nd string ";
    gets(d);
    cout<<i<<endl<<c<<endl<<d;
    return 0;
}





请帮帮我



我尝试了什么:



我尝试将变量i作为char,然后仅使用gets()来获取输入,这样可以完美地工作

但是我确实需要把它作为一个整数,在某些程序中,能够做一些像增量/减量/无论什么



Please help me out

What I have tried:

I have tried taking variable i as char, then taking the input using only gets()'s, which works flawlessly
but then i strictly need to take it as an integer, in some programs, to be able to do stuff like increment/decrement/whatever

推荐答案

这是因为 cin 只读取构造变量 i 所需的字符数量。之后输入缓冲区仍然包含直到输入行末尾的其他字符或空格,包括末尾的换行符。因此,对获取的调用将仅返回该数据,而不是等待来自用户的更多输入。您应该使用 cin.getline 来使用这些额外的字符,还要读取完整的字符串,而不是使用获取。
That is because cin reads only the amount of characters necessary to construct the variable i. After which the input buffer still contains other characters or whitespace up to the end of the input line, including the newline character(s) at the end. So the call to gets will return just that data, rather than waiting for more input from the user. You should use cin.getline to consume those extra characters, and also to read in complete strings, rather than using gets.


什么是错误的 C ++ 字符串和流?

What's wrong with C++ strings and streams?
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int i;
    string c,d;
    cout<<"Enter int ";
    cin>>i;
    cout<<"Enter string ";
    cin >> c;
    cout<<"Enter 2nd string ";
    cin >> d;
    cout<<i<<endl<<c<<endl<<d<<endl;
    return 0;
}


这篇关于为什么第一个get()在这段代码中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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