首页 > 解决方案 > 为什么这段代码编译失败?

问题描述

我正在尝试使用 C++ 并在下面写了这段代码-

 // BalancedStrings.cpp : Defines the entry point for the console application.
//


#include <iostream>
#include <stack>
#include "stdafx.h"

using namespace std;

bool isBalanced(string s) {
    stack<char> stack;
    char l;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
            stack.push(s[i]);
            continue;
        }
        if (stack.empty())
            return false;

        switch (s[i]) {
        case ')':
            l = stack.top();
            stack.pop();
            if (l == '{' || l == '[')
                return false;
        case '}':
            l = stack.top();
            stack.pop();
            if (l == '(' || l == '[')
                return false;
            break;


        case ']':
            l = stack.top();
            stack.pop();
            if (l == '{' || l == '(')
                return false;
            break;

        }



    }
    
    return true;

}





int main()
{
    string s1 = "{}";
    
    
    std::cout << isBalanced(s1);
    
    
    return 0;
}

然而,当我试图编译这段代码时,我遇到了很多编译错误,比如'C2039'cout': is not a member of 'std', C2065 'string': undeclared identifier 等。我能够编译代码通过将标题#include "stdafx.h" 移动到顶部。所以我想更深入地了解,改变头文件的顺序是如何让我的代码编译成功的。

标签: c++visual-studiovisual-c++

解决方案


推荐阅读