[英]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 ?
但是,如何在输入位置和输出字符的周围进行其他操作呢?
Do I use atoi
? 我会使用
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. 为简洁起见,没有进行错误检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.