#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    27
    Rep Power
    0

    Input taking spaces by default


    In the below program when am reading input from keyboard its taking only 2 characters instead of 4 and remaining 2 characters its taking spaces by default.
    why is it???

    // reversestring.cpp : Defines the entry point for the console application.
    //
    Code:
    /*program to take char input through pointers*/
    #include "stdafx.h"
    #include "stdio.h"
    #include "conio.h"
    #include "stdlib.h"
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	int c,inc,arrysize;
    	char *revstring;
    	printf("enter the size of char arry:");
    	scanf("%d",&arrysize);
    	revstring = (char *)malloc(arrysize * sizeof(*revstring));
    	printf("%d",sizeof(revstring));
    	printf("enter the array elements:");
    	for(inc=0;inc<arrysize;inc++)
    	{
    	scanf("%c",&revstring[inc]);
    	
    	}
    	for(inc =0;inc<arrysize;inc++)
    		printf("%c",revstring[inc]);
    	getch();
    	return 0;
    
    
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,365
    Rep Power
    1870
    > printf("%d",sizeof(revstring));
    This will just print the size of a pointer, not the amount of memory it points to (which you already know).

    > scanf("%c",&revstring[inc]);
    This will typically read the \n left behind by you previous scanf("%d" call.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    27
    Rep Power
    0
    That means do you want me to take the input through getchar()
    or fgets();
  6. #4
  7. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,365
    Rep Power
    1870
    Reading every line using fgets(), then parsing it however you want is generally a good way to go.

    The code might be a few lines longer(*), but the outcome is far more predictable.

    (*) actually, by the time you've added all the error checking to simple scanf calls, the amount of code is pretty much the same.

    Comments on this post

    • Technovicez agrees : Thankz a ton
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo