0

I am trying to get hands on in C++ and have written this below piece of code--

 // 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;
}

However, when I tried to compile this code I ran into a lot of compilation errors like 'C2039'cout': is not a member of 'std', C2065 'string': undeclared identifier etc. I was able to get the code compile by moving the header #include "stdafx.h" to the top. So I wanted to understand deeper, how does changing the order of the header file could get my code compile successfully.

user496934
  • 3,822
  • 10
  • 45
  • 64
  • 1
    You should also be able to get the code to compile by removing stdafx.h completely. As an extra bonus your code will even compile on Linux! – Sam Varshavchik Jul 03 '21 at 13:09
  • You will find many comments to avoid 'using namespace std; as it is simply a heavy load on your compiler and can cause confusion. I suggest being more aware of package contents. (See cppreference.com) For example if you use later compiler standards such as "-std=c++17" (on g++), THEN, after '#include ' add lines similar to 'using std::cout, std::endl;' Now cout and endl will be known from the iostream package. – 2785528 Jul 03 '21 at 13:29
  • 1
    The first thing to do is remove `#include "stdafx.h"`. That's a Microsoft compile-time optimization; you don't need it, and it often creates problems. – Pete Becker Jul 03 '21 at 14:58
  • @2785528 -- a minor point: you comment is correct, but C++ does not have packages. In the standard it would be the "iostream library", which I have always thought was confusing. In general, I'd say something like "Now `cout` and `endl` will be known from the `` header. – Pete Becker Jul 03 '21 at 15:04

0 Answers0