【发布时间】:2018-07-02 19:37:22
【问题描述】:
我需要在 C++ 中读取一个文件并保存每一行(在一个向量中),因为我稍后会处理它们。
我还需要保存一个 char* 向量,它将指向每个字符串*的第一个位置。
问题是我不知道如何将string* 分配给char*。
仅供参考,我不能使用const char*,它必须是char*。
代码:
void ClassA::readFile() {
std::ifstream file("test.txt");
std::string* str = new string();
while (std::getline(file, *str))
{
_aVector.push_back(*str);
char *c = &str[0]; <-- This works if string is not declared as string*
char *c = .... <--What is the equivalent for string*
str = new string();
someFunction(c); <-- This function saves the *c in a vector.
}
}
【问题讨论】:
-
为什么需要存储
char*的?这样做的目的是什么? -
这是我的一个约束。
-
&(*str)[0]可以解决问题——尽管这是 C++98,但不能保证整个字符串是连续的(参见 stackoverflow.com/questions/1986966/…) -
您需要分配
string和new的机会非常小。 -
我猜你不能使用
string::c_str(),因为它是const?如果您不需要修改字符串,那将是一个选项并且更清晰。
标签: c++ string char readfile c++98