【发布时间】:2021-12-21 19:51:00
【问题描述】:
我试图输入一串字符,只分别输出最后一个字符和第一个字符。下面是我正在使用的代码。
#include<stdio.h>
int main(){
for(int i=0;i<3;i++){
int n; // length of the string
char string[101];
scanf("%d %s", &n, &string);
fflush(stdin); // sometimes I also use getchar();
printf("%c%c", string[n+1], string[0]);
}
printf("\n");
return 0;
}
我正在使用 for 循环,因为我想输入字符串 3 次,但是当我运行代码时,输入不是我所期望的。如果我输入例如
5 abcde
输出
a //there's space before the a
你能帮我看看我哪里出错了吗?
输入:
5 abcde
6 qwerty
3 ijk
预期输出:
ea
yq
ki
【问题讨论】:
-
C 中的数组使用从 0 开始的索引。所以如果字符串有5个字符,最后一个字符是
string[4]。 -
查看here 了解
fflush(stdin)。 -
不要让用户就字符串的长度对你撒谎(无论是意外还是故意),您应该使用
strlen(string)来查找字符串的实际长度。 -
好的,感谢 cmets