How do I run C++ code in Qt? [solved]



  • Hi I have following code:

    @#include <QCoreApplication>

    using namespace std;

    unsigned long factfunc(unsigned long);

    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);

    int n;
    unsigned long fact;
    
    cout << "Enter an integer: ";
    cin >> n;
    
    fact = factfunc(n);
    
    cout << "Factorial of " << n << " is " << fact << endl;
    
    return a.exec&#40;&#41;;
    

    }

    unsigned long factfunc(unsigned long n)
    {
    if(n>1)
    return n * factfunc(n-1);
    else
    return 1;
    }
    @

    Errors: cout & cin was not declared in this scope

    Probably I cannot use namespace std here. Do I need to do something else to use
    C++ code in Qt? I will be writing a lot of C++ code here so please help.



  • Are your including the headers, I think below should do the trick?

    @#include <iostream>@



  • u have to use std::cout and std::cin in spite of cout and cin and please include <stdio.h> and <iostream.h>



  • You would use the std:: element if you weren't using the namespace, so it should work without that. I know some don't like using namespaces and would only use the above approach.

    The stdio.h header file is a C rather than C++ header file, so it shouldn't effect the standard library use.

    The iostream header file should be used without the .h as that signfies you are using an older version, the newer standard libaries use headers without the extensions.



  • Yes that definitely did the trick. The following code runs ok. Thanks mlkeosoft

    @#include <QCoreApplication>
    #include <iostream>

    using namespace std;

    unsigned long factfunc(unsigned long);

    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);

    int n;
    unsigned long fact;
    
    cout << "Enter an integer: ";
    cin >> n;
    
    fact = factfunc(n);
    
    cout << "Factorial of " << n << " is " << fact << endl;
    
    return a.exec(&#41;;
    

    }

    unsigned long factfunc(unsigned long n)
    {
    if(n>1)
    return n * factfunc(n-1);
    else
    return 1;
    }
    @

    How do I mark this post as solved?



  • To mark it as solved just edit your original post and prepend or append "[solved]" to the title.



  • [quote author="ankursaxena" date="1393418751"]u have to use std::cout and std::cin in spite of cout and cin and please include <stdio.h> and <iostream.h>[/quote]

    Why does he need to include "<stdio.h>"? And why he has to use std::cout since he included "usine namespace std;"



  • thanx mikeosoft! you are right. He just need <iostream> .


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.