int main() { char str[N]; int arr[N]; int i = 0; char* t; int j,a,count; printf("please input strings\n"); scanf("%c",str[i]); while(str[i] != '0') { i++; count++; } while(i != 0) { for(j=(i-1);j>=0;j--) { if(str[i] < str[j]) { strcpy(t,str[j]); strcpy(str[j],str[i]); strcpy(str[i],t); } } i--; } printf("%s",str); return 0; }
时间: 2024-02-14 17:12:20 浏览: 22
这段代码中有一些问题,需要进行修改:
1. 首先,在输入字符串时应该使用 `scanf("%c", &str[i])` 而不是 `scanf("%c", str[i])`,因为 `%c` 格式控制符需要传入字符的地址,而不是字符本身。
2. 在输入字符串时应该使用循环,而不是只读取一个字符。可以使用 `fgets` 函数来读取一整行字符串。
3. 在排序时,应该使用 `str[j] > str[i]` 而不是 `str[i] < str[j]`,因为如果 `str[i]` 比 `str[j]` 小,就不需要交换它们的位置了。
4. 在交换字符串的位置时,应该使用 `strcpy` 函数来实现,而不是直接赋值。
5. 在输出结果时,应该输出字符串的前 `count` 个字符,而不是整个字符串。
综上所述,修改后的代码如下:
```c++
#include <stdio.h>
#include <string.h>
#define N 100
int main() {
char str[N];
int arr[N];
int i = 0;
char t;
int j, a, count = 0;
printf("please input strings:\n");
fgets(str, N, stdin);
while (str[i] != '0') {
i++;
count++;
}
i--;
while (i >= 0) {
for (j = i - 1; j >= 0; j--) {
if (str[j] > str[i]) {
t = str[j];
str[j] = str[i];
str[i] = t;
}
}
i--;
}
for (i = 0; i < count; i++) {
printf("%c", str[i]);
}
return 0;
}
```
以上代码中,我们使用 `fgets` 函数来读取一整行字符串,然后对字符串进行冒泡排序,最后输出排序后的结果。