
-----------------------------------
aldreneo
Fri May 05, 2006 7:50 pm

My C code is acting strange
-----------------------------------
What I want the code to output(red is stuff I typed blue is stuff the computer outputted):
>test
test
>test with spaces
test with spaces
>


#include

main( )
{
 int loop;
 while(loop>=0)
 {
  char i;
   printf( ">" );
   scanf( "%s", &i ); 
   printf( "%s \n", &i );
 }
}

But this is what I get as an output (Stuff in red is what I typed stuff in blue is what the computer outputted):
>test
test
>test with spaces
test
>with
>spaces
>


Gcc latest

-----------------------------------
Tony
Fri May 05, 2006 8:03 pm


-----------------------------------
is this a joke? how familiar are you with C?

-----------------------------------
aldreneo
Fri May 05, 2006 8:08 pm


-----------------------------------
Not much....more used to c++ why?  is it something stupid?

-----------------------------------
Tony
Fri May 05, 2006 8:24 pm


-----------------------------------
I don't think you know C++ well ether..

#include

main( )
{
 int loop; =0)  =0)
    {
        char i;
        printf( ">" );
        gets( &i ); 
        printf( "%s \n",&i );
    }
}


Here is one possible way of writing it would be (that is proper)

#include

main( )
{
    int loop = 0;
    while(loop>=0)
    {
        char buffer

Notice how the variable loop is initialized to be 0 before it's used? If you don't initialize a varaible then it's value is undefined (it could be anything). Also note that buffer is an array of characters. In C char is a single character, whereas strings are stored as a null-terminated array of characters.

-----------------------------------
rizzix
Sat May 06, 2006 3:14 pm


-----------------------------------
That too, is not safe. What happens if the user enters 256 or more characters?

Simply put: gets is unsafe by design. Don't use it in this manner (i.e. to get strings).
