簡體   English   中英

將標准字符串轉換為char *的方法不同

[英]Difference in methods for converting std string to char*

我知道有很多關於如何將std :: string轉換為char *的問題,通過研究,我采用了幾種不同的選擇。 但是,似乎唯一適合我的方法是c_str()方法中的const_cast。

因此,我暫時使用該方法,但想了解有關其他方法為何不起作用的更多信息。 我為何無法按預期工作,這似乎對其他許多人都有用,但我的理解尚不足。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    char* test = "Hello World";
    string testStr(test);

    vector<char> testVec2(testStr.begin(), testStr.end());
    // testVec2[0] = 'F';
    char* test2 = reinterpret_cast<char*>(testVec2.data());

    vector<char> testVec3(testStr.begin(), testStr.end());
    // testVec3[0] = 'G'; 
    char* test3 = &testVec3[0];

    // The only one that works
    char* test4 = const_cast<char*>(testStr.c_str());

    cout << "char* test: " << test << " [" << strlen(test) << "]" << endl;
    cout << "str test: " << testStr << " [" << testStr.length() << "]" <<     endl;
    cout << "=== conv testing === " << endl;
    cout << "char* test2: " << test2 << " [" << strlen(test2) << "]" <<     endl;
    cout << "char* test3: " << test3 << " [" << strlen(test3) << "]" << endl;
    cout << "char* test4: " << test4 << " [" << strlen(test4) << "]" << endl;

    cin.get();
    return 0;
}

我知道使用const_cast的隱患,但目前適用於我的情況。 我只是簡單地從用戶那里獲取字符串,將其傳遞給C API,並且對其不做任何處理(不必擔心被修改)。

這是輸出示例https://imgur.com/a/2S1HD

那么我在做錯什么,還有更好的方法嗎?


更新感謝大家的快速答復。 似乎我的內在困惑是假設空終止符不在我分配給char *變量的新緩沖區中。 因此,為什么我的輸出在字符串后顯示隨機字符(這應該是我的線索,但是自從完成C / C ++以來已經很久了)

我也應該最初對此C ++ 17進行標記(自修復以來),因為這是我的目標。 我沒有在Visual Studio的控制台應用程序中啟用該功能,該功能使Passer By的解決方案無法正常工作。 這就是我今后將使用的方法。

底線,將我的目標更改為C ++ 17,這可以按預期工作

char* test = "Hello World";
string testStr(test);
vector<char> testVec2(testStr.begin(), testStr.end());  
char* test2 = testStr.data();
vector<char> testVec2(testStr.begin(), testStr.end());

這將創建以下向量:

vector<char> testVec2 = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};

有什么從你身上跳下來嗎? 這應該。 它不包含空終止符。 因此,任何嘗試將testVec2.data()用作C字符串都將導致未定義行為。

盡管從C++11 std::string的基礎緩沖區必須包含空終止符,但begin - end范圍不包含該字符。

在C ++ 17中,從std::string獲取char*的最簡單方法是

std::string str = "Why is this only available since C++17?";
some_c_function(str.data());

至於為什么其他方法不起作用,請參考bolov的答案

c++11 ,從std::string獲取非常量 char*的最佳方法是使用以下代碼:

std::string s = "hello";

my_non_const_correct_c_function(&s[0]); // better than using const_cast

如果在未聲明conststd::string上使用const_cast ,則可能會遇到未定義的行為

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM