4

最近的一个问题中,我了解到在某些情况下您只需要通过 achar*而不是 a std::string。我真的很喜欢string,对于我只需要传递不可变字符串的情况,它可以很好地使用.c_str(). 在我看来,利用字符串类易于操作是一个好主意。但是,对于需要输入的函数,我最终会执行以下操作:

std::string str;
char* cstr = new char[500]; // I figure dynamic allocation is a good idea just
getstr(cstr);               // in case I want the user to input the limit or
str = cstr;                 // something. Not sure if it matters.
delete[] cstr;
printw(str.c_str());

显然,这不是那么,呃,直截了当。现在,我对 C++ 还很陌生,所以我真的不能只见树木不见森林。在这种情况下,每个输入都必须转换为 C 字符串并返回以利用string's 的有用方法,这只是一个更好的主意并习惯于 C 风格的字符串操作吗?这种不断的来回转换是否太愚蠢而无法处理?

4

2 回答 2

3

std::string在您给出的示例中,您通常可以使用该std::getline函数将一行读入 a : http ://www.cplusplus.com/reference/string/getline/

当然,这并不能做 curses 库所做的一切。如果您需要一个非常量char*以便某些 C 函数可以读入它,您可以使用vector<char>. 您可以vector<char>从 a创建 a string,反之亦然:

std::string       a("hello, world");
std::vector<char> b(a.begin(), a.end());

// if we want a string consisting of every byte in the vector
std::string       c(b.begin(), b.end());

// if we want a string only up to a NUL terminator in the vector
b.push_back(0);
std::string       d(&b[0]);

所以你的例子变成:

std::vector<char> cstr(500);
getnstr(&cstr[0], 500);
printw(&cstr[0]);
于 2010-11-03T02:04:37.987 回答
1

大多数 std::string::c_str() 实现(如果不是全部)只是简单地返回一个指向内部缓冲区的指针。没有任何开销。

但是请注意 c_str() 返回的是 a const char*,而不是 char*。并且函数调用后指针将变为无效。因此,如果函数执行诸如写回传递的字符串或复制指针之类的操作,则不能使用它。

于 2010-11-03T01:50:01.277 回答