我正在寫一個函數,根據特定字符的位置將C++ string
分成兩個獨立的string
。但是,當我使用它返回的指針時,它們似乎是無效的。這裏有一個例子:`std :: string :: substr`返回無效指針?
#include <iostream>
#include <string>
bool SplitString(std::string &input, char splitChar, std::string **left, std::string **right)
{
std::string::size_type offset = input.find(splitChar);
if (offset == std::string::npos) return false;
*left = &input.substr(0, offset);
*right = &input.substr(offset + 1);
return true;
}
int main(int argc, char *argv[])
{
std::string input = "Left side:Right side";
std::string *left;
std::string *right;
if (SplitString(input, ':', &left, &right)) {
std::cout << "left = \"" << *left << "\"" << std::endl;
std::cout << "right = \"" << *right << "\"" << std::endl;
} else {
std::cout << "Didn't find ':' - this shouldn't happen!" << std::endl;
}
return 0;
}
這應該輸出如下:
left = "Left side"
right = "Right side"
爲什麼不工作?
爲什麼不直接發送對這些函數的字符串引用?爲什麼所有的指針都瘋了? – PaulMcKenzie 2014-10-20 01:31:20
這就是你得到一個右值的地址。 – 2014-10-20 01:31:25
stdd :: string :: substr不返回一個std :: string *,它返回一個std :: string。你得到一個返回值的地址,當你調用你的第二個std :: string :: substr時,它將被覆蓋。只需複製字符串。擺脫所有這些指針,並使用std :: string。 – Ben 2014-10-20 01:44:46