Mac版VSCode中STL函数无法使用,请求技术帮助
问题修复方案
核心代码错误修正
你的代码存在两个关键问题,直接引发STL栈函数的编译报错:
栈类型不匹配
你声明了stack<int> st;,但实际要存入的是string类型的单词,类型不兼容导致push()等函数调用失败。需将栈的类型改为string:stack<string> st;输入读取不完整
cin >> s;只会读取第一个空格前的内容,无法获取带空格的完整句子。替换为getline读取整行输入:getline(cin, s);
修正后的完整代码
#include <iostream> #include <stack> #include <string> using namespace std; void reverseSentence(string s) { stack<string> st; for (int i = 0; i < s.length(); i++) { string word = ""; while (s[i] != ' ' && i < s.length()) { word += s[i]; i++; } st.push(word); } while (!st.empty()) { cout << st.top() << " "; st.pop(); } cout << endl; } int main() { string s; getline(cin, s); reverseSentence(s); return 0; }
MacOS环境编译补充说明
若修正后仍有异常,检查以下两点:
- 编译时指定C标准版本,比如使用C17:
g++ -std=c++17 your_code.cpp -o reverse_sentence - 确认Xcode Command Line Tools安装完整,可执行
xcode-select --install重新安装
内容的提问来源于stack exchange,提问作者Anjali Kedia
相关产品推荐
相关产品推荐

