使用string函数 从键盘输入三个字符串 按大小顺序输出
时间: 2023-05-30 18:07:15 浏览: 57
以下是使用string函数从键盘输入三个字符串,按大小顺序输出的示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2, str3;
cout << "请输入三个字符串:" << endl;
cin >> str1 >> str2 >> str3;
if (str1 > str2) {
swap(str1, str2);
}
if (str1 > str3) {
swap(str1, str3);
}
if (str2 > str3) {
swap(str2, str3);
}
cout << "按大小顺序输出为:" << endl;
cout << str1 << endl << str2 << endl << str3 << endl;
return 0;
}
```
运行该程序,可以得到类似如下的输出结果:
```
请输入三个字符串:
hello world
apple
banana
按大小顺序输出为:
apple
banana
hello world
```
相关问题
从键盘输入3个字符串,按由小到大排序(使用strcmp函数
好的,可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], str3[100];
printf("请输入三个字符串:\n");
scanf("%s %s %s", str1, str2, str3);
// 使用strcmp比较字符串大小,进行排序
if (strcmp(str1, str2) > 0) {
char temp[100];
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
if (strcmp(str1, str3) > 0) {
char temp[100];
strcpy(temp, str1);
strcpy(str1, str3);
strcpy(str3, temp);
}
if (strcmp(str2, str3) > 0) {
char temp[100];
strcpy(temp, str2);
strcpy(str2, str3);
strcpy(str3, temp);
}
printf("排序后的字符串为:\n");
printf("%s\n%s\n%s\n", str1, str2, str3);
return 0;
}
```
输入三个字符串后,程序会使用strcmp函数进行比较,然后按照从小到大的顺序进行排序输出。
用c语言写,从键盘输入3个字符串,按由小到大排序,使用strcmp函数
好的,以下是用C语言编写的程序,可以实现从键盘输入3个字符串,并按由小到大排序,使用strcmp函数:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], str3[100], temp[100];
printf("请输入三个字符串:\n");
scanf("%s%s%s", str1, str2, str3);
if (strcmp(str1, str2) > 0) {
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
if (strcmp(str1, str3) > 0) {
strcpy(temp, str1);
strcpy(str1, str3);
strcpy(str3, temp);
}
if (strcmp(str2, str3) > 0) {
strcpy(temp, str2);
strcpy(str2, str3);
strcpy(str3, temp);
}
printf("排序后的结果为:\n");
printf("%s\n%s\n%s\n", str1, str2, str3);
return 0;
}
```
在这个程序中,首先定义了4个字符数组,分别用于存储3个输入的字符串和一个中间变量。然后通过scanf函数从键盘输入3个字符串。接下来使用strcmp函数对3个字符串进行比较,并根据比较结果交换它们的位置,使得它们按由小到大的顺序排列。最后使用printf函数输出排序后的结果。