0
#include<stdio.h>
#include<stdlib.h>
int main(){
   int n;
   scanf("%d",&n);
   char str[101];
   for(int i=0;i<n;i++){
      scanf("%s ",&str[i]);
   }
   printf("%s ",str);
}

I am getting the output without space For exammple if input is (a p p l e) i am getting (apple) but i need to get (a p p l e)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • What is the value , you are providing to n ? – Hritik Sharma Mar 17 '22 at 14:21
  • 3
    You are reading multiple strings into one variable, offset from each other and overlapping. – stark Mar 17 '22 at 14:24
  • 2
    `scanf(%s)` stops at the first whitespace. You cannot scan strings with spaces that way. – Gerhardh Mar 17 '22 at 14:24
  • You probably need to look into `fgets`. very important: Read this: https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input, otherwise you'll get some surprises. – Jabberwocky Mar 17 '22 at 14:27

3 Answers3

1

The format "%s" is used to read a sequence of characters until a white space is encountered,

Instead of the conversion specifier %s use the conversion specifier %c if you are going to use a loop.

For example

int i = 0;

while ( i < n && scanf( "%c", str + i ) == 1 && str[i] != '\n' ) ++i;
str[i] = '\0';

Instead of the loop you could use the standard function fgets as for example

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

//...

fgets( str, n + 1, stdin );
str[ strcspn( str, "\n" ) ] = '\0';

puts( str );

Pay attention to that the expression n + 1 shall be not greater than 101 due to this declaration

char str[101];
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

In your last printf you are just calling the String, you're not putting spaces.

You need another for to call the String letter by letter, and put spaces between them.

Like this:

#include<stdio.h>
#include<stdlib.h>
int main(){
   int n;
   scanf("%d",&n);
   char str[101];
   for(int i=0;i<n;i++){
      scanf("%s ",&str[i]);
   }
   for(int i=0;i<n;i++){
           printf("%c ",str[i]);
      }
}
Bernardo Almeida
  • 419
  • 4
  • 12
0

If you change your scanf to scanf(" %[^\n]",&str[i]); you should get your desired result. %s looks for whitespace-separated strings, while %[^\n] will takes the entire string up to a newline.

SGeorgiades
  • 1,771
  • 1
  • 11
  • 11