c - 通过输入c中的位置来查找字符串的字符

标签 c

您好,我知道有很多您输入字符并输出字符位置的示例。但是如何在输入位置和输出字符的地方反过来做呢?

  • 输入字符串:abcdefghijklmnopqrstuvwxyz
  • 输入位置:0
  • 输出:第0位的字符是'a'

我使用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");
     }   

}

关于c - 通过输入c中的位置来查找字符串的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50390054/

相关文章:

c - 如何使用 LD_PRELOAD 检查是否已预加载 linux 共享库

c++ - 如何以优雅的方式转储 XML?

c++ - 宏 ((void(*)())0)() 是什么意思?

c - 错误: dereferencing pointer to incomplete type when accessing struct

Int值的组合

c - 如何在c中编写一个读取数组的函数?

c - 错误的 Visual C float / double 转换?

c - 在Linux的net/ipv4/udp.c中,为什么UDP数据包需要通过xfrm4_policy_check()来处理?

c - 栈和堆的区别

c - fork(3) 和 fork(2) 的区别