[英]Error “no match for 'operator+” when concatenating strings
我正在嘗試使用以下代碼反轉字符串中的單詞:
#include <bits/stdc++.h>
using namespace std;
int main()
{
//_ _ the sky is blue
string vec;
getline(cin, vec);
stack<string> str;
string temp = "";
string ans = "";
for (int i = 0; i < vec.length(); i++)
{
if (vec.at(i) == ' ')
{
if (temp.length() > 0)
{
str.push(temp);
temp = "";
}
else
{
temp = temp + vec.at(i);
}
}
}
//ans = ans + temp;
while (!str.empty())
{
ans = ans + " " + str.pop();
}
if (ans.length() != 0 && ans.at(0) == ' ')
ans = ans.substr(1);
cout << ans << endl;
}
我在第 33 行收到此錯誤,告訴"no match for 'operator+'"
。
我附上了相關的截圖:
請幫忙。
pop()
是一個返回類型為void
的stack
成員方法,它不返回string
,因此不能打印,也不能與其他字符串連接。
正如錯誤所示,您不能使用+
運算符為這兩種不同類型添加void
和string
(除非您通過重載+
運算符使該選項可用),所以ans = ans + " " + str.pop();
是錯的。
你可以使用:
while (!str.empty())
{
ans = ans + " " + str.top();
str.pop();
}
由於top()
確實返回了一個string
object。
我應該指出,使用#include <bits/stdc++.h>
是不好的, using namespace std
也不是很好,但是將它們放在一起是一場等待發生的災難。
容器適配器std::stack
的方法pop
具有返回類型void
。 所以這個說法
ans= ans+" "+str.pop();
不正確,編譯器將發出錯誤。
你需要寫類似的東西
while(!str.empty()){
ans= ans+" "+ str.top();
str.pop();
}
注意這個for循環
for(int i=0 ; i<vec.length(); i++){
if(vec.at(i)==' '){
if(temp.length()>0){
str.push(temp);
temp = "";
}
else{
temp = temp + vec.at(i);
}
}
}
有一個錯誤。 如果存儲在 object vec
中的字符串不以空格字符結尾,則不會將字符串的最后一個單詞壓入堆棧。
看來您正在嘗試做的是以下內容。
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
int main()
{
std::string s( " Hello World " );
std::stack<std::string> st;
std::cout << "\"" << s << "\"\n";
for ( std::string::size_type i = 0; i < s.size(); )
{
std::string tmp;
while ( i < s.size() && isspace( ( unsigned char )s[i] ) )
{
tmp += s[i++];
}
if ( !tmp.empty() )
{
st.push( tmp );
tmp.clear();
}
while ( i < s.size() && !isspace( ( unsigned char )s[i] ) )
{
tmp += s[i++];
}
if ( !tmp.empty() )
{
st.push( tmp );
}
}
std::string result;
while ( !st.empty() )
{
result += st.top();
st.pop();
}
std::cout << "\"" << result << "\"\n";
return 0;
}
程序 output 是
" Hello World "
" World Hello "
謝謝你們幫助我。 這是代碼並且工作得很好:
#include <bits/stdc++.h>
using namespace std;
int main(){
//_ _ the sky is blue
string vec;
getline(cin, vec);
stack<string>str;
string rs;
string temp="";
string ans= "";
for(int i=0 ; i<vec.length(); i++){
if(vec.at(i)==' '){
if(temp.length()>0){
str.push(temp);
temp = "";
}
}
else{
temp = temp + vec.at(i);
}
}
ans = ans + temp;
while(!str.empty()){
ans= ans+" "+str.top();
str.pop();
}
if(ans.length() != 0 && ans.at(0) == ' '){
ans = ans.substr(1);
}
cout<<ans<<endl;
reverse( ans.begin(), ans.end());
cout<<ans<<endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.