0

I tried to write a function that inserts space at regular intervals in a string. If a[50] is a string, and n is the preferred interval from the user, insert_space(a,b,len,n) will insert blanks after the n'th column and will store the modified string in b.

#include <stdio.h>
int getinput(char temp[]);
void insert_space(char s1[],char s2[],int,int);
int main ()
{
    int n, len;
    char a[100], b[100];
    printf("Enter the nth column number for inserting\n");
    scanf("%d",&n);
    printf("Enter the line\n");
    len=getinput(a);
    insert_space(a,b,len,n);
    printf("%s\n",b);

}
void insert_space(char s1[],char s2[],int len, int n)
{
    int i=0, c=0,flag=0;
    for(i=0;i<=len;i++)
    {  
        if(flag!=n)
        {
            s2[c]=s1[i];
            c++;
            flag++;
        }
        else
        {
            s2[c]=' ';
            i=i-1;
            c++;
            flag=0;
        }          
    }
    s2[c]='\0';
}
int getinput(char temp[])
{
    int c, i=0;
while((c=getchar())!=EOF)
    {
        temp[i]=c;
        i++;
    }
    i--;
    temp[i]='\0';
    return i;
}

I entered the values of the string a as abcdefghijkmnop. Instead of "abdce fghij kmnop" as the ouput in b, I got "abcd efghi jkmno p" as the output. I'm not sure what I did wrong here. edit: After just including the insert_function code, I've edited it to include the entire execution code.

  • The value of input for integer n was 5 in the above execution. – Udhay Sankar Aug 05 '18 at 13:54
  • 1
    This sounds like an excellent problem to solve using a debugger....and it will learn you how to use your debugger. – Paul Ogilvie Aug 05 '18 at 14:09
  • 2
    just out of curiosity: Why have you skipped **l**? – Inrin Aug 05 '18 at 14:21
  • The code works fine on my side. Are you sure the input was correct? – Shahe Ansar Aug 05 '18 at 14:44
  • When run with a main program consisting of `int main(void) { char a[50] = "abcdefghijkmnop"; char b[50]; insert_space(a, b, strlen(a), 5); printf("Before: [%s]\n", a); printf("After: [%s]\n", b); return 0; }`, I get the output: `Before: [abcdefghijkmnop]` — `After: [abcde fghij kmnop ]`. This has more or less the expected behaviour; there's a trailing blank added, but that falls within the specification, it would seem. In other words, if you aren't getting to see that behaviour, then maybe you aren't running the code you think you're running (recompile?). – Jonathan Leffler Aug 05 '18 at 14:55
  • @H.S. There are many possible ways that they could be running into issues. I've shown a simple test program which suggests that the code is OK. The onus is now on the OP to produce an MCVE ([MCVE]) analogous to (but different from) the one I showed that illustrates the problem. The way I printed the data with explicit markers around the text string (I used `[` and `]`) helps make it easier to see what's in the output. – Jonathan Leffler Aug 05 '18 at 15:12
  • @JonathanLeffler, I tried to do an MCVE and couldn't decide on what to include and what not to. So, I edited the original code to include the entire execution code instead of just the function. – Udhay Sankar Aug 05 '18 at 15:37
  • @PaulOgilvie, I know debugging is the process of removing bugs, but I have no idea how to use a debugger. – Udhay Sankar Aug 05 '18 at 15:39
  • 1
    The `scanf("%d", &n)` leaves a newline (and any other characters after the number) in the input, to be read by the `getchar()` loop. So, there is an extra newline at the start of the 'string' you read. If you did as I showed and suggested and printed the data with markers before and after the string, this would be self-evident. You probably have a newline at the end of the input too, and hence at the end of the output as well. – Jonathan Leffler Aug 05 '18 at 15:42
  • Except that I voted to close as 'cannot reproduce', I'd now vote to close as a duplicate of [`scanf()` leaves the newline character in the input buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer). – Jonathan Leffler Aug 05 '18 at 15:44
  • Udhay, then it is time to read the manual, start the debugger and do your first steps in really really debugging: it is generally not possible without one. It is part of learning C. – Paul Ogilvie Aug 05 '18 at 16:04
  • @JonathanLeffler. So, scanf() leaves a newline after reading, everytime the function is called. Here the new line was read by the getchar loop. Thanks a lot, that cleared it up for me. Will use markers in the future for such programs. – Udhay Sankar Aug 05 '18 at 16:09
  • @PaulOgilvie, yes I'll do so from now on. I'm still a newbie so, I'm learning things slowly. It is great that stackoverflow exists for beginners like me. :-) – Udhay Sankar Aug 05 '18 at 16:13
  • More precisely, when `scanf()` completes an input such as `%d`, it leaves the character that wasn't part of the number — which might be a newline, but might be a letter or space or punctuation character (you might have typed `5 green bottles`) — behind to be processed by the next input operation. As applied to your code, though, and assuming you hit return/enter immediately after typing 5, then yes, you're right: the newline was there for the `getchar()` loop to read. Putting start and end markers around printed strings can clarify a lot of otherwise mysterious problems. – Jonathan Leffler Aug 05 '18 at 16:14
  • @Jonathan Leffler. Yes, I got it. If I were to leave a blank after typing 5, the first element in the string a would be a blank. – Udhay Sankar Aug 05 '18 at 16:17

1 Answers1

1

There is a \n ,newline (Enter) from scanf("%d",&n); which is recorded as a[0]. So you have to manage this UN-handled newline (Enter).

To solve this, add an extra c = getchar(); before loop while ((c = getchar()) != EOF) in function int getinput(char temp[]), to handle that extra newline left behind by scanf("%d",&n);

Modified code:-

#include <stdio.h>
int getinput(char temp[]);
void insert_space(char s1[], char s2[], int, int);
int main()
{
    int n, len;
    char a[100], b[100];
    printf("Enter the nth column number for inserting\n");
    scanf("%d", &n);
    printf("Enter the line\n");
    len = getinput(a);
    insert_space(a, b, len, n);
    printf("%s\n", b);
}

void insert_space(char s1[], char s2[], int len, int n)
{
    int i = 0, c = 0, flag = 0;
    for (i = 0; i <= len; i++)
    {
        if (flag != n)
        {
            s2[c] = s1[i];
            c++;
            flag++;
        }
        else
        {
            s2[c] = ' ';
            i = i - 1;
            c++;
            flag = 0;
        }
    }
    s2[c] = '\0';
}

int getinput(char temp[])
{
    int c, i = 0;
    c = getchar(); // to handle extra newline from scanf
    while ((c = getchar()) != EOF)
    {
        temp[i] = c;
        i++;
    }
    i--;
    temp[i] = '\0';
    return i;
}

Output :-

Enter the nth column number for inserting
5
Enter the line
abcdefghijkmnop
abcde fghij kmnop 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
anoopknr
  • 3,177
  • 2
  • 23
  • 33
  • Your use of one `getchar()` assumes that the user did not type `5 green bottles` in response to the prompt. The user might even just type a space after the `5` before the newline. It is probably best to either (1) read lines (`fgets()`) and parse them with `sscanf()`, or (2) gobble to newline or EOF — `while ((c = getchar()) != EOF && c != '\n') ;`. – Jonathan Leffler Aug 05 '18 at 16:17