+ 1
Finding a letter in the string which corresponds to that number.
You are making a program that works with text. It needs to take a word and an index number from input, and output the letter with that index in the word. Task: Take a string and a number from input, then output the letter in the string, which corresponds to that number.
6 Réponses
+ 5
Prakash Kumar Jaiswal if you initialize the input buffer, filling it with nulls, then you can reliably determine whether the index is out of range simply by checking for null.
#include <stdio.h>
int main() {
char word[50] = {}; //all nulls
unsigned int position;
scanf("%49s",word); //limit length
scanf("%u", &position);
if(position<50 && word[position])
printf("%c\n", word[position]);
else
puts("Position is out of range.");
return 0;
}
+ 3
Prakash Kumar Jaiswal
you can still iterate even without using strlen, just stop when you hit the null terminator '\0'.
#include <stdio.h>
int main() {
char word[50];
int position;
scanf("%s",word);
scanf("%d", &position);
for(int i=0;word[i]!='\0';i++){
if(word[i]==word[position]){
printf("%c\n", word[i]);
return 0;
}
}
puts("Position is out of range.");
return 0;
}
+ 2
Show your efforts first!
+ 2
Prakash Kumar Jaiswal please follow the forum guidelines
https://www.sololearn.com/discuss/1316935/?ref=app
https://www.sololearn.com/discuss/3021159/?ref=app
+ 2
BroFar ,
Thanks for the detailed information, I'm looking forward to next time whenever I post a problem.
+ 1
`ᴴᵗᵗየ , I already solved this problem but I stuck in without using the string library file. Is it possible to perform the same operation without using the string library file. My effort was this:
#include <stdio.h>
#include<string.h>
int main() {
char word[50];
int position;
scanf("%s",word);
scanf("%d", &position);
// Check if the index is valid
if (position >= 0 && position < strlen(word)) {
printf("%c\n", word[position]);
} else {
printf("Position is out of range.\n");
}
return 0;
}