从字符到字符串的无效转换

boboobobo

在我的代码中,我创建了一个字符串,并将该字符串推入堆栈。(我不知道我做的是否正确,因为我是C ++和堆栈概念的新手。)但是当我尝试置顶(我认为这输出了堆栈中的第一个元素)时,它无法正常工作。我遇到了从char到string的转换问题。即使我将其强制转换为char,它也无法正常工作。有什么办法可以转换吗?我正在努力把它付诸实践。

我不断收到错误消息:

C:\ main.cpp:15:37:错误:无效的用户定义的从'char'到'std :: stack> :: value_type && {aka std :: basic_string &&}'的转换[-fpermissive] nextWord.push(str [ i + 1]);

#include <iostream>
#include <iomanip>
#include <map>
#include <string.h>
#include <stack>

using namespace std;

int main(){
std::stack<string> nextWord;
string str = "T<h>is is a test";

for(int i = 0; i < str.length(); i++){
    if (str[i + 2] == '>' && str[i] ==  '<'){
        nextWord.push(str[i + 1]);
    }
}
while (!nextWord.empty()) {
    cout << "String: " << nextWord.top();;
}

cout << nextWord.pop() << '>' ;
}
戴尔

问题是这一行:

nextWord.push(str[i + 1]);

str[i + 1]是一个char,您正在尝试将其推入字符串堆栈。更改为此,它应该可以正常工作:

nextWord.push(string(1, str[i + 1]));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章