字符串推回问题的矢量,你们能帮我吗?

Vector of string push back problem, can you guys help me?

本文关键字:问题 字符串      更新时间:2023-10-16

我正在创建一个小程序来测试向量类。
我正在使用字符串向量,然后我读取了一个文本文件,我试图在向量中写下每个单词(每个空格 1 个单词(。
当我尝试使用 push_back 以便将字符串放入向量时,会出现一个错误,说"没有将字符串转换为字符的函数"。

如果我犯了一些英语错误,对不起。
感谢您的帮助。

我阅读了一些解释如何工作push_back的指南,但在本教程的所有内容中都使用此声明。

vector<string> v_of_string;<br/>
//allocate some memeory<br/>
v_of_string[1].pushback(string to punt in the vector);<br/>

我的代码

int main() {
vector<string> str; 
//allocate some memory 
ifstream iFile("test.txt"); 
int i = 0;
if (iFile.is_open()) {       
while (!iFile.eof()) {
string temp;
iFile >> temp;
str[i].push_back(temp);
cout << str[i];
i++;
}
iFile.close();
}
return 0;
}

所以

str[i].push_back(temp);

是一个错误,你的意思是

str.push_back(temp);

push_back整个向量,而不是向量的一个特定元素,因此不需要[i]。我希望如果你回到你的指南,那么它会说同样的话。

您还可以将cout << str[i];替换为cout << str.back();,以始终输出向量的最后一个元素。所以实际上你根本不需要变量i

while (!iFile.eof()) {
string temp;
iFile >> temp;

不正确,应该是

string temp;
while (iFile >> temp) {

有关解释,请参阅此处。如果您也从指南中得到此代码,我会很感兴趣。在 while 循环中使用eofC++一定是我们在堆栈溢出中看到的最常见的错误。

顺便说一句str恕我直言,向量变量的名称选择不佳。