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
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
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()) != '\n')
{
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
Good luck!!
Bruno
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 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
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
Good luck,
Bruno
Use getchar() in between scanf and gets like
scanf("%d ",&t);
getchar();
gets(alphabet);
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) +