riyaz2609
riyaz2609

Reputation: 67

I used cin to get a string input as shown below in the code and it works fine. Is it alright?

#include<iostream>
#include<stdio>

using namespace std;

int main()
{   int n;
    char s[15];
    cin>>n;
    cin>>s;
    cout<<n*2<<"\n";
    cout<<s;
    return 0;
}

I tried with gets and fgets function but they don't work just after cin..

Upvotes: 0

Views: 30

Answers (1)

demogorgon
demogorgon

Reputation: 484

I'm kind of confused on what you are asking here, but I have noticed something here that can be fixed.

Yes the code you have compiles and it works. However, it could be improved. When prompted to input something to your char array, you'll notice that it will not accept whitespaces. So if I input, Jon Smith, the output will only be Jon and the rest of the string input is cut off. To fix this, you will need to make a call the the getline() function.

The documentation of getline() states:

Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n'..)

This will allow you to get whitespaces from the input and put the entire input back into a string.

If you add this function call to your code where the second input prompt lies and you were to run the code, you would notice that you will only get prompted once and then the program would finish running before the second prompt appears to be executed. This is because getline() does not ignore leading whitespace characters and it stops reading any further because the cin>> before it is seen as a newline character.

To make getline() work with cin>>, you must use cin.ignore() before the call to getline(). Below is some code that I wrote to make this adjustment:

// Example program
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int n;
    string s; //using string allows us to use getline()

    cout<<"Enter a number: "; //Let user know they are being prompt for number
    cin>>n;
    cin.ignore(); //ignore the leading newline

    cout<<"Enter a string: "; //let user know being prompt for string
    getline (cin,s);

    cout<<n*2<<"\n";
    cout<<s;
    return 0;
}

Again, the code you have works and compiles. I'm not sure if my solution is the answer you are hoping to get but I hope that you are able to find this useful! Cheers!

Upvotes: 1

Related Questions