Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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>>


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


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
Posted
Updated 6-Nov-16 23:10pm
v3
Comments
CPallini 7-Nov-16 4:39am    
Don't mix C++ streams with C stdio, unless you really know what you are doing, see, for instance:
http://www.drdobbs.com/the-standard-librarian-iostreams-and-std/184401305

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.
 
Share this answer
 
Comments
CPallini 7-Nov-16 4:38am    
5.
What's wrong with C++ strings and streams?
C++
#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;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900