Question

I was having issues with another program. It was something like this:

if(n < 15000)
{
    printf("I am < 15000");
return 0;
}
else if(n > 19000)
{
    printf("I am > 19000");
    return 0;
}
else if(n > 51000)
{
    printf("I am > 51000");
    return 0;
}

If n was above 51000 then it would still return "I am > 19000". I figured I needed to "close the gap" by using else if(n > 19000 && n < 51000) so to test this I wrote this program:

#include <iostream>
int main()
{
    printf("Please enter a #: ");
    int block;
    cin >> n;
    if(n <= 10 )
    {
        printf("I am <= 10");
        return 0;
    }
    else if(n <= 15000)
    {
        printf("I am <= 15000");
        return 0;
    }
    else if(n > 15000 && n <= 19000)
    {
        printf("I am > 15000 and <= 19000");
        return 0;
    }
    else if(n > 19000)
    {
        printf("I am > 19000");
        return 0;
    }
    else if(n > 51000)
    {
        printf("I am > 51000");
        return 0;
    }
}

Trying to compile this gave me this error: "error: ‘cin’ was not declared in this scope" I am using g++ <filename> to compile on mac osx 10.7

Était-ce utile?

La solution

Either use C++ standard input/output streams or use C standard input/outpur streams. It is a bad idea to mix them.

All standard declarations with very rare exceptions are placed in the standard name space std

So instead of

cin >> n;

you should write

std::cin >> n;

Or place the following directive before using cin

using std::cin;
//,,,
cin >> n;

Also you should include header <cstdio> where function printf is declared.

Take into account that this condition

else if(n > 19000)

is invalid because it includes all numbers greater than 10000 including numbers greater than 51000

I would write the program the following way

#include <iostream>

int main()
{
    std::cout << "Please enter a #: ";
    int block;
    std::cin >> n;

    if ( n <= 10 )
    {
        std::cout << "I am <= 10";
    }
    else if ( n <= 15000 )
    {
        std::cout << "I am <= 15000";
    }
    else if ( n <= 19000)
    {
        std::cout << "I am > 15000 and <= 19000";
    }
    else if ( n > 19000 && n <= 51000 )
    {
        std::cout << "I am > 19000";
    }
    else if ( n > 51000 )
    {
        std::cout << "I am > 51000";
    }

    std::cout << std::endl; 
}

Autres conseils

by

#include <iostream>

you are including symbols in namespace std, so to access standard input stream you have to write:

std::cin

Maybe std::cin >> n would help? Seems like an issue of a namespace to me.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top