c - Adding characters at the end of a string -


i trying add characters @ end of string using following code. not getting desired output.

#include<stdio.h>         #include<stdlib.h>        #include<string.h>        int main()    {     int l,i;     char a[30];     printf("enter \n");        scanf("%s",a);        l=strlen(a);        for(i=l;i<(29-l);i++)          {           scanf("%c",&a[i]);           a[i+1]='\0';          printf("\n%s",a);          }      return 0;        }      

i guess, problem whitespace. after enter first string, there still newline \n in input buffer. when read 1 character scanf, newline , not character entered.

you can skip whitespace, when prefix format string space

scanf(" %c",&a[i]); 

now append character entered @ end of string.

update:

from scanf

the format string consists of sequence of directives describe how process sequence of input characters.
...
• sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). directive matches amount of white space, including none, in input.

this means, when insert space in format string, skip white-space in input.

this happen automatically other input directives %s or %d. %c takes next character, if white-space char. therefore, if want skip white-space in case, must tell scanf inserting space in format string.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -