Problem in reading a string

char alphabet[27];
char givenSentence[101];int t;
scanf("%d ",&t);

How do I avoid space as the first digit of alphabet?

Input is like : 5 ghdgfdh


This is how I would do it:

#include <stdio.h>

int main()
	int i,j,t=0;
	char sentence[100];
	scanf("%d ", &i);
	while((j=getchar()) != '\n')
		sentence[t] = j;
	sentence[t+1] = '\0';
	int x, num = 0;
	for(x=0; sentence[x] != '\0';x++)
	printf("String has %d characters ", num);
	return 0;

You can run it and test it with a string such as abc and the answer is that the string has exactly 3 characters :smiley:

Good luck!!


Avoid using gets.

In C, simply use-

scanf("%s", alphabet);

In C++, use-

cin >> alphabet;

They take care of white space. And in fact can’t be used to read strings with space in them.

Both the above solutions give a nice idea to you @arnabbcs08 >> I would some other alternative here:

After you read the testcases, put a dummy getchar() to take the space. and then take the string following it anyway you would like.

Disclaimer: You would have at least changed the Example ( 5 ghdgfdh ), this clearly implies you are asking for the TOTR problem of the live March Challenge. I have answered this assuming that it does not prove out to be any kind of unfair means in the Live Contest. And for any such involvement, I would not be responsible.


The issue arnabbcs08 had was simply with C syntax regarding reading a string :slight_smile: This is, by no means, a key step towards actually code a correct algorithm to solve this problem, so, if as much, we only provided some guidance on small syntax details, and there’s nothing wrong with it :slight_smile:

Also, kudos @arnabbcs08 for not asking directly: “Help me with this contest question, getting RTE…” or something similar… By providing a clear and precise question on a small detail, we can and are generally more willing to help you :wink:

Good luck,


Use getchar() in between scanf and gets like

scanf("%d ",&t);


1 Like

the reason why space is coming in your string is.

after u call scanf for the integer 5, the space given after it stored in the buffer.
gets has the property that it takes input from the buffer, so when u called gets it took (Since it was already in buffer) +