如何从字符串转换为字符*

问题描述

我有这段代码,我需要在其中输入一些数据,然后程序需要将数据按字母顺序排列。

问题是我无法将 string name 转换为 char* 变量 s1s2

要输入的数据:

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;
    }
}

解决方法

甚至不需要在代码中使用 C 字符串。换3行

char* s1 = ...;
char* s2 = ...;

const std::string &s1 = ...;
const std::string &s2 = ...;

if (strcmp(s1,s2) > 0)

if (s1 > s2) {

并且您可以保留std::string

#include <array>
#include <iostream>
#include <string>

struct obiectiv {
    int id;
    std::string name;
    double latitud; 
    double longitud; 
    double cost_vizitare;
};

int main()
{
    std::array<obiectiv,9> ob;
    std::cout << "Introduceti obiectivele(maxim 9): ID NAME LATITUD LONGITUD PRICE" << '\n';
    for (int i = 0; i < 9; i++) {
        std::cin >> ob[i].id >> ob[i].name >> ob[i].latitud >> ob[i].longitud >> ob[i].cost_vizitare;
    }

    auto tempob = ob;
    
    for (int k = 0; k < 9;k++) {
        bool sorted = true;
        for (int i = 0; i < 9; i++) {
            const auto &s1 = tempob[i].name;
            const auto &s2 = tempob[i + 1].name;
            if (s1 > s2) {
                std::swap(tempob[i],tempob[i + 1]);
                sorted = false;
            }
        }
        if (sorted) {
            break;
        }
    }
    std::cout << "alphabetical order: ";
    for (int i = 0; i < 9; i++) {
        std::cout << tempob[i].name << '\n';
    }
}

交换逻辑有错误。我将其替换为 std::swap 以修复错误。

使用 std::array 代替 C 数组允许您复制数组而无需循环。

我还在代码中更改了一些不好的样式。我在 using namespace std; 初始化之前删除了 structstruct、不必要的 std::endl 并将 sorted 设为布尔值。

,

可以通过多种不同的方式执行此操作(从字符串转换为字符*):

1.使用 const_cast 操作符:

@Log
@Configuration
@EnableStateMachineFactory
public class EmployeeStateMachineConfig extends StateMachineConfigurerAdapter<EmployeeStates,EmployeeEvents> {


    private static final String EMPLOYEE_ID = "employeeId";


    @Override
    public void configure(StateMachineTransitionConfigurer<EmployeeStates,EmployeeEvents> transitions) throws Exception {

        transitions

            .withExternal().source(EmployeeStates.ADDED).target(EmployeeStates.IN_CHECK).event(EmployeeEvents.CHECK)

            .and()
            .withExternal().source(EmployeeStates.IN_CHECK).target(EmployeeStates.APPROVED).event(EmployeeEvents.APPROVE)

            .and()
            .withExternal().source(EmployeeStates.APPROVED).target(EmployeeStates.ACTIVE).event(EmployeeEvents.ACTIVE);

    }

    @Override
    public void configure(StateMachineStateConfigurer<EmployeeStates,EmployeeEvents> states) throws Exception {

        states.withStates()
            .initial(EmployeeStates.ADDED)
            .stateEntry(EmployeeStates.ADDED,context -> {

                Long employeeId = (Long) context.getExtendedState().getVariables().getOrDefault(EMPLOYEE_ID,-1L);

                log.info("Employee with id: " + employeeId + " is added to the platform.");
                log.info("entering ADDED state.");

            })

            .state(EmployeeStates.IN_CHECK)
            .state(EmployeeStates.APPROVED)

            .end(EmployeeStates.ACTIVE);
    }
}

2.使用strcpy():

std::string str = "from string to char*";
char *chr = const_cast<char*>(str.c_str());
std::cout << chr << "\n";

3.使用copy():

std::string str = "from string to char*";
char *chr = strcpy(new char[str.length() + 1],str.c_str());
std::cout << chr << "\n";

4.使用 std::string 的连续存储:

std::string str = "from string to char*";
int length = str.size();
char *chr = new char[length + 1];
std::copy(str.begin(),str.end(),chr);
chr[length] = "\0";//add end of line
std::cout << chr << "\n";
delete[] chr; //don't forget!