Problem in reading a string

strings

#1

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

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

Input is like : 5 ghdgfdh


#2

Hello,

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()) != '

')
{
sentence[t] = j;
t++;
}
sentence[t+1] = ‘\0’;

	int x, num = 0;
	for(x=0; sentence[x] != '\0';x++)
	num++;
	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!!

Bruno


#3

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.


#4

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.


#5

@bugkiller,

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,

Bruno


#6

Use getchar() in between scanf and gets like

scanf("%d ",&t);

getchar();

gets(alphabet);

#7

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) +