views:

36

answers:

2

Hello. I am trying to get more adept and my C programming and I was attempting to test out displaying a character from the input stream while inside of the loop that is getting the character. I am using the getchar() method.

I am getting an exception thrown at the time that the printf statement in my code is present. (If I comment out the printf line in this function, the exception is not thrown).

Exception: Unhandled exception at 0x611c91ad (msvcr90d.dll) in firstOS.exe: 0xC0000005: Access violation reading location 0x00002573.

Here is the code... Any thoughts? Thank you.

PS. I am using the stdio.h library.

/*getCommandPromptNew - obtains a string command prompt.*/
void getCommandPromptNew(char s[], int lim){    

    int i, c;

    for(i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i){
        s[i] = c;
        printf('%s', c);
    }

}

+3  A: 

Try changing:

printf('%s', c);

to

printf("%c", c);

If you wish to print the entire string at the end of the loop you need to terminate it with a NULL char as:

s[i] = 0;

and then you can print it as:

printf("%s", s);
codaddict
thanks! Works great.
Shane Larson
+1  A: 

First thing that you should check is: are you allocated memory for s[] or not.
Second: printf("%c", c); // I can suppose that %s - is waiting for null terminated string.
Third: maybe problem with "" vs '' in printf().

Thank you for your input as well.
Shane Larson