简体   繁体   中英

Find the character of a string by inputting the position in c

Hi I know that there are alot of examples where you input a character to and output the position of the character. But how do you do it the other way around where you input the position and output the character ?

  • input string: abcdefghijklmnopqrstuvwxyz
  • input position: 0
  • output: The character in position 0 is 'a'

Do I use atoi ?

int main(void) {

char line[SIZE];
int position;

// int character = getchar(); //get string
scanf("%d\n", &position); //get position
int i = 0;
while(fgets(line, SIZE, stdin) != NULL) {
    if(line[i] == position) { 
       printf("The character in postion %d is '%c'\n", position,line[i]);   
        //flag = TRUE;
   // }
    i++;
}       

return 0;
}
while(fgets(line, SIZE, stdin) != NULL) 

  {

     line[strlen(line)-1] = '\0'; // as fgets append '\n' before '\0', replacing '\n' with '\0'
     if(strlen(line) > position)
     {   
           printf("The character in postion %d is '%c'\n", position,line[position]); 
     }   
     else
     {   
        printf("invalid position\n");
     }   

}

You probably want this:

#include <stdio.h>

#define SIZE 100

int main(void) {    
  char line[SIZE];
  int position;

  scanf("%d", &position); //get position
  getchar();   // absorb \n from scanf (yes scanf is somewhat odd)

  while (fgets(line, SIZE, stdin) != NULL) {
      printf("The character in postion %d is '%c'\n", position, line[position]);
  }

  return 0;
}

No out of range check whatsoever is done here for brevity

Example of execution:

1
abc
The character in postion 1 is 'b'
Hello
The character in postion 1 is 'e'
TEST
The character in postion 1 is 'E'

This small example may help too:

#include <stdio.h>

#define SIZE 100

int main(void) {
  char line[SIZE];

  fgets(line, SIZE, stdin);
  for (int i = 0; line[i] != 0; i++)
  {
    printf("The character in postion %d is '%c'\n", i, line[i]);
  }
}

No error checks done either for brevity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM