Thread: Sting and Char Funny Problem

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

    Sting and Char Funny Problem

    I try to get Strng first then get Character from user. But it wont work, the process of getting character will be skipped. But when i try get char first then string, it works! Please assist. TY
    Code:
    #include <stdio.h>
    
    int main (){
    	
    	char singleChar;
    	char text[30]={0};
    	int count;
    	
    	printf("String:");
    	scanf("%s", text);
    	
    	printf("Character:");
    	scanf("%c", &singleChar);
    	//singleChar will automatically proceed without getting input from user
    	//But when Char is get before String, No problem.
    	
    //Test Result
    	printf("\nCharacter: %c\n",singleChar);
    	printf("String: %s\n",text);
    
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You're being tripped up by the newline char that scanf() leaves behind in the income stream (keyboard buffer).

    Add:
    getchar();

    After the first scanf(), and all will be well.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Referring to message 1...
    On line 13 ad a single space between the " and %c ... scanf(" %c".... This will tell scanf to skip over anything left in the input buffer.

  4. #4
    Registered User
    Join Date
    Aug 2011
    Posts
    102
    Thanks. Both of them works. I love the 2nd one

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with probably a very simple char sting issue
    By Prometheus in forum C++ Programming
    Replies: 14
    Last Post: 01-10-2007, 08:02 PM
  2. Help - Function returning a sting
    By AmiTsur in forum C Programming
    Replies: 1
    Last Post: 11-08-2002, 07:47 AM
  3. converting int to sting
    By LWisne in forum C++ Programming
    Replies: 7
    Last Post: 10-14-2002, 08:07 AM
  4. ctime and sting copy
    By Sue Paterniti in forum C Programming
    Replies: 9
    Last Post: 04-21-2002, 10:04 PM
  5. Sting Manipulation!!Pls Help
    By vij30 in forum C Programming
    Replies: 3
    Last Post: 03-15-2002, 01:43 PM