Program Crash

This is a discussion on Program Crash within the C Programming forums, part of the General Programming Boards category; Why does the following code crash under MSVC++ 2010, and give unexpected output under turbo c , if a space ...

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    385

    Program Crash

    Why does the following code crash under MSVC++ 2010, and give unexpected output under turbo c , if a space is not given between '%s' and '%c' in scanf....

    Code:
    #include <stdio.h>
    
    int main()
    {
    	char c,name1[15];
    
    	scanf("%s%c",name1,&c);
    	printf("\n%s %c",name1,c);
            return 0;
    }
    Last edited by juice; 11-18-2011 at 11:02 PM.

  2. #2
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    It's fine on MSVC 2010 when I try it. What are you giving as input? How do you mean "crash"?

  3. #3
    Registered User
    Join Date
    Aug 2011
    Posts
    385
    program was crashing because I forgot an ampersand befor c in scanf, but the output is still weird.

  4. #4
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Your problem is the behavior of scanf. %s reads up to the first whitespace, %c reads the whitespace, and last character goes unread. A space before a %c tells scanf to ignore all leading whitespace.

  5. #5
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    And without the space between the, scanf will keep reading stuff that matches %s and not put anything in c until you hit enter, then it'll put the newline in c (because the newline doesn't match %s but does match %c).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why does this program crash when I do this?
    By Witch in forum C Programming
    Replies: 4
    Last Post: 03-18-2010, 08:10 PM
  2. program crash
    By l2u in forum C++ Programming
    Replies: 11
    Last Post: 09-07-2006, 01:58 PM
  3. Why Does My Program Crash?
    By Grantyt3 in forum C++ Programming
    Replies: 20
    Last Post: 09-29-2005, 06:34 PM
  4. Why does the program crash?
    By SkyRaign in forum C++ Programming
    Replies: 8
    Last Post: 09-25-2005, 11:06 AM
  5. Program crash ?!
    By tilex in forum C++ Programming
    Replies: 6
    Last Post: 12-21-2004, 08:47 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21