I am trying to write a simple program that stores a user input in a c-string,and will then print out each character (I)diaganolly across screen and (II) each character on a new line.

The problem im having with this,and with c strings entirely,is that it keeps printing out random characters that are stored in the array,after it has printed out the ones that have been input into it.

For example:

    char user_input[10];
    int setnum ; // set precision number

    cin >> user_input;

    for(int i=0; i < 10 ; i++)
        cout << user_input[i] ;
        cout << endl;


is supposed to display each char on a new line,which it does,but then displays random characters until the end of array.

Is there anyway to stop this?

7 Years
Discussion Span
Last Post by StaticX

Strings in C are terminated by a '\0' character, but there is no magic that stops loops on it. Nothing stops you from walking past that character if the loop does not account for it. Change your loop to something like this and it will stop in the right place:

for(int i = 0; i < 10 && user_input[i] != '\0'; ++i)
    /* print user_input[i] */

This will make sure your loop stops when '\0' is found or the limit of the array is reached. To be strictly safe in C++, you should also limit cin when reading the string:

cin >> setw(10) >> user_input;

In C you can do the same thing with scanf():

scanf("%9s", user_input);

Edited by Tom Gunn: n/a


Thanks for the quick reply.I had tried a similar method earlier and it wouldnt work,taking a quick look at your code it turned out iv been using '/0' instead of '\0' as the null character.Its all fixed now,thanks again for your help.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.