Home > Enterprise >  Visual Studio 2022 behaving wierdly in C , not showing errors in code
Visual Studio 2022 behaving wierdly in C , not showing errors in code

Time:10-06

I'm currently learning C and encountered a strange behavior of VS. Errors are not showing up in code (even though IntelliSense is enabled - I checked settings) and the lines in error list are probably wrong too.

main.cpp:

#include <iostream>
#include <string>
#include "fraction.h"

using namespace std;
int main()
{
    fraction a = fraction::fraction(2, -4);
    cout << a.toString();
}

fraction.h:

#pragma once
#include <string>

class fraction
{
private:
    int a;
    int b;

    void Optimise()
    {
        if (b < 0)
        {
            a = -a;
            b = -b;
        }

        if (a % b == 0 || b % a == 0)
        {
            for (int i = 2; i <= b; i  )
            {
                if (a % i == 0 && b % i == 0)
                {
                    a /= i;
                    b /= i;
                }
            }
        }
    }

public:
    fraction(int numerator, int denominator)
    {
        a = numerator;
        if (denominator != 0)
        {
            b = denominator;
        }
        else
        {
            //exception
        }

        Optimise();
    }

    string toString()
    {
        return a   "/"   b;
    }
};

Code looks normal in text editor, however it won't compile and it shows these errors

Thanks for help! :)

Edit: The reason was not writing std:: in front of strings in fraction.h, but VS did not highlight the error, see long answer below.

CodePudding user response:

The reason for the code for not compiling was not writing std::string or using namespace std at the top in fraction.h as @molbdnilo has pointed out. What confused me, was that VS highlighted the code and knew I ment to write std::, but the compiler did not.

Also, I would like to point out my mistake (which has nothing to do with compiler) in my work with strings (since I'm still learning).

Instead of:

string toString()
{
    return a   "/"   b;
}

Should be:

std::string toString()
{
    return std::to_string(a)   "/"   std::to_string(b);
}
  • Related