嗨我知道有很多例子可以输入一个字符并输出字符的位置。但是,你如何在输入位置并输出角色的其他方面做到这一点?
我使用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;
}
答案 0 :(得分:1)
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");
}
}
答案 1 :(得分:1)
你可能想要这个:
#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;
}
为了简洁起见,没有超出范围的检查
执行示例:
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'
这个小例子也有帮助:
#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]);
}
}
为简洁起见,没有进行错误检查。