CHANDRU T K
CHANDRU T K

Reputation: 13

How to print leading spaces before char array in C?

#include <stdio.h>
int main() {

char a[30];
char b[30];
scanf("%[^\n]s",a);
scanf(" %[^\n]s",b);
printf("%s \n",a);
printf("%s",b);
return 0;
}

Input :

    hai
        hello

Output :

    hai
hello

But I am expecting

    hai
        hello

How to print leading spaces before hello?

Upvotes: 1

Views: 243

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753535

Note that %[…] (a scan set) is a complete conversion specification. The s after it in your code never matches anything, but you can't spot that. The newline is left in the input. You'd have to arrange to read that before using the second scan set — and a space (or newline) in the format string is not the answer to that. Replacing the s with %*c would do the job. But you're probably best off not using scanf() at this point; use fgets() instead.

Using scanf()

#include <stdio.h>

int main(void)
{
    char a[30];
    char b[30];
    if (scanf("%29[^\n]%*c", a) == 1 &&
        scanf("%29[^\n]%*c", b) == 1)
    {
        printf("[%s]\n", a);
        printf("[%s]\n", b);
    }
    return 0;
}

Input:

    hai
        hello

Output:

[    hai]
[        hello]

Using fgets()

#include <stdio.h>
#include <string.h>

int main(void)
{
    char a[30];
    char b[30];
    if (fgets(a, sizeof(a), stdin) != 0 &&
        fgets(b, sizeof(b), stdin) != 0)
    {
        a[strcspn(a, "\n")] = '\0';
        b[strcspn(b, "\n")] = '\0';
        printf("[%s]\n", a);
        printf("[%s]\n", b);
    }
    return 0;
}

For the same input, this produces the same output.

Upvotes: 1

Harvett
Harvett

Reputation: 178

You may try fgets:

#include <stdio.h>
int main() {
  char a[30];
  char b[30];
  fgets(a, 30, stdin);
  fgets(b, 30, stdin);
  printf("%s \n",a);
  printf("%s",b);
  return 0;
}

Upvotes: 0

Related Questions