字符串推回问题的矢量,你们能帮我吗?
Vector of string push back problem, can you guys help me?
我正在创建一个小程序来测试向量类。
我正在使用字符串向量,然后我读取了一个文本文件,我试图在向量中写下每个单词(每个空格 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 循环中使用eof
C++一定是我们在堆栈溢出中看到的最常见的错误。
顺便说一句str
恕我直言,向量变量的名称选择不佳。
相关文章:
- 编译包含字符串的代码时遇到问题
- setlocale的C++土耳其字符串问题
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 我的逻辑反转字符串中的元音有什么问题?
- 按字母顺序对C++问题中的子字符串索引进行分区
- 用户输入字符串的文件附加问题..C++
- 使用 minijson-reader 库读取 JSON 字符串时出现问题
- 在将字符串放入字符串向量时遇到问题?
- 将文件复制到自定义位置,存在字符串转换问题
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 不确定出了什么问题(字符串输入)
- 反向和计数字符串的 C++ 问题
- 反转具有返回值的字符串时出现问题
- C++字符串问题-如何访问字符串元素
- public:静态常量字符串声明/初始化问题
- 在MySql中使用字符串操作函数有什么问题
- Libwesockets.h:lws_write:C++字符串到C的转换和发送问题
- 问题:字符串在另一个字符串上写入
- 日志文件输出的问题-字符串和c_str之间的差异- c++