Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How to enter a string character by character from the user?

sabbaglearnersabbaglearner pakistanMember Posts: 2
edited June 2016 in C and C++

I've written the code but it's not working.
Code is as follows:

        int main()
        {
            int size=25;
            char c,huma[size];
            int i;
            while(i<size && c!='\n')
            {

                cin>>c;
                huma[i]=c;
                i++;
            }
            huma[i]='\0';
            cout<<huma;

        }
Tagged:

Best Answer

  • sabbaglearnersabbaglearner pakistanMember Posts: 2
    Accepted Answer

    Ok ! But still it's not working. Actually the loop is not terminating whether I press 'enter' or the size limit exceeds. And Hence the entered loop is not displayed at the end.

Answers

  • B00B00 Member Posts: 106 ✭✭✭
    edited June 2016

    Your i has radom value at the start. ALWAYS set initial values for variables to avoid problems.
    Variable without a value does not mean it will be 0 or anything else that you expect.

  • B00B00 Member Posts: 106 ✭✭✭

    cin is whitespace delimited, so any whitespace (including \n) will be discarded. c will never be \n.
    You can use the getline method to get the line, then istringstream to get formatted input from the line. Or alternatively use C function fgets.

Sign In or Register to comment.