【发布时间】:2021-05-27 07:56:07
【问题描述】:
我有这段代码,我需要在其中输入一些数据,然后程序需要将数据按字母顺序排列。
问题是我无法将string name 转换为char* 变量s1 和s2。
要输入的数据:
1 Cheile_Dobrogei 45 25 200
2 Vulcanii_Noroiosi 46 25 50
3 Cetatea_Istra 45 25 100
4 Barajul_Siriu 51 30 50
5 Castelul_Peles 45 30 150
6 Castelul_Bran 53 30 150
7 Voronet 54 35 200
8 Cheile_Bicazului 55 35 100
9 Manastirea_Varatec 56 35 50
#include <iostream>
#include <string>
using namespace std;
struct obiectiv {
int id;
string name;
double latitud;
double longitud;
double cost_vizitare;
};
int main()
{
int i, k, temp;
struct obiectiv ob[9];
cout << "Introduceti obiectivele(maxim 9): ID NAME LATITUD LONGITUD PRICE" << endl;
for (i = 0; i < 9; i++) {
cin >> ob[i].id >> ob[i].name >> ob[i].latitud >> ob[i].longitud >> ob[i].cost_vizitare;
}
struct obiectiv tempob[9];
struct obiectiv t[9];
for (i = 0;i < 9;i++) {
tempob[i] = ob[i];
}
int sorted;
for (k = 0; k < 9;k++) {
sorted = 1;
for (i = 0;i < 9;i++) {
char* s1 = tempob[i].name;
char* s2 = tempob[i + 1].name;
if (strcmp(s1,s2) > 0) {
t[i] = ob[i];
tempob[i] = tempob[i + 1];
tempob[i + 1] = t[i];
sorted = 0;
}
}
if (sorted == 1) {
break;
}
}
cout << "alphabetical order: ";
for (i = 0; i < 9; i++) {
cout << tempob[i].name << endl;
}
}
【问题讨论】:
-
char* s1 = tempob[i].name.c_str(); -
@JerryJeremiah
c_str()返回一个const char*,它不能分配给char*。因此s1和s2需要被声明为const char*(首选),或者c_str()返回的指针需要使用const_cast类型转换为char*(不太首选)。 -
你为什么还要使用 C 字符串?使用字符串
const std::string &s1 = ...;、const std::string &s2 = ...;并将if (strcmp(s1,s2) > 0)替换为if (s1 > s2) { -
那么为什么需要
char *而不是const char *?为什么不使用std::string中内置的比较运算符? -
@RemyLebeau 实际上你只需要
char* s1 = &tempob[i].name[0];,如果你真的想要char*。不需要const_cast
标签: c++ string pointers char alphabetical