This is just a small program I wrote to find a problem with a larger one. Everything changes when I add the line with scanf. I know it is not safe, I read other threads concerning printf errors, but i would like to know how to write this correctly using printf.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
char message  = "amfdalkfaklmdklfamd.";
com = message;
int i = 1;
while (i !=4)
printf ("%s \n", com);
I don't get compile time errors but "message" isn't printed even once.
Btw, i read suggestions about using fgets instead of scanf but as "message" size is variable I don't want to state a fixed size of input.
message size is not variable. It is a fixed sized array.
Btw, I think the problem is with the initialization of message. In C++, it should be done this way: char message='a','m','f',...; since it is an array of characters, and not a pointer to characters.
Is your problem with line 11? What is the value of i and what is the result of the while conditional expression? Will a different expression make it operate differently?
Try placing some printf statements like "Made it into while loop" in various places before during & after the while loop. This is a kind of poor man's debugging, using a real debugger is much easier.
Btw, if you use a scanf , you need to test to see if worked, otherwise you run the risk of having uninitialised variables, or initialised variables that have garbage put in them . Look up what the scanf function returns, and make use of that value. A switch statement is handy when when more than 1 value is read in. Beware of of newlines left in the buffer, they can mess up successive calls to scanf.
You have two bugs here. First, before the scanf(), add fflush(stdout). stdout is buffered and this is why you aren't seeing the output before the scanf().
The second bug is in your use of scanf(). You're assuming that scanf() will read the string somewhere and then change word to point to it. Scanf() doesn't work that way. It will copy the string in the memory that word points to. So word needs to be a buffer containing enough space already. For example: char word;
This is why scanf("%s") is a bad idea: there's usually no way to know how big the buffer needs to be.
IdeasMan, I did and nothing bad happened. My problem was with initialization of the variable word. Now this small program works fine but the bigger program doesn't and I just can't see why.
dhayden, what would you suggest instead of scanf? And now that my mini program works, I can see the output at the end, but in the bigger program It never appears, even though everything else looks fine. Could this be repaired also with fflush?