我想要做的是首先输入一个数字,这将决定我要输入多少个字符(例如 n = 4),然后用户将输入他们想要的字符(例如 line = abcd)。然后他们可以指定字符的顺序(例如输入:4 3 2 1 和输出:dcba)。
int main() {
int n;
scanf("%d", &n); fgetc(stdin);
char characters[n + 1];
fgets(characters, n + 1, stdin);
char orderedChars[n + 1];
for (int i = 0; i < n; i++) {
int index;
scanf("%d", &index);
orderedChars[i] = characters[index - 1];
}
printf("%s", orderedChars);
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试打印出数组时,它会打印出来,dcba??a而不仅仅是dcba,但是当我不断将 1 添加到 时n,一个 Unicode 字符会消失,直到 7+ 才不会成为问题。(简单表示)
n = 5
Char's: abcde
Order: 5 4 3 2 1
Output: edcba?a
n = 6
Char's: abcdef
Order: 6 5 4 3 2 1
Output: fedcbaa
n = 7
Char's: abcdefg
Order: 7 6 5 4 3 2 1
Output: gfedcba
Run Code Online (Sandbox Code Playgroud)
前四行似乎是正确的,但我不知道它是否也与 for 循环内的代码有关,或者与scanf我如何打印数组有关。
orderedChars 未初始化且其初始值不确定。
%sinprintf()要求传递的缓冲区以空字符结尾。
添加终止空字符以避免麻烦。
#include <stdio.h>
int main() {
int n;
scanf("%d", &n); fgetc(stdin);
char characters[n + 1];
fgets(characters, n + 1, stdin);
char orderedChars[n + 1];
for (int i = 0; i < n; i++) {
int index;
scanf("%d", &index);
orderedChars[i] = characters[index - 1];
}
orderedChars[n] = '\0'; /* add this */
printf("%s", orderedChars);
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是告诉printf()打印的长度。在这种情况下,您不必分配终止空字符。
#include <stdio.h>
int main() {
int n;
scanf("%d", &n); fgetc(stdin);
char characters[n + 1];
fgets(characters, n + 1, stdin);
char orderedChars[n]; /* only n elements are required instead of n + 1 */
for (int i = 0; i < n; i++) {
int index;
scanf("%d", &index);
orderedChars[i] = characters[index - 1];
}
printf("%.*s", n, orderedChars); /* add .* to the format and add the length n */
}
Run Code Online (Sandbox Code Playgroud)