Search code examples
c++functionscopedeclare

C++ Getting an error with my functions


Need some homework help. I'm new to C++, and I'm getting an error I don't understand. Here's my code:

/*
 * homework6.cpp
 * Coder: omega9380
 * Final Project
 */

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main () {

    void welcomeScreen();
    void printLine( int length );

    welcomeScreen();

    return 0;
}

void welcomeScreen() {
    string userName = "";
    string title1 = "CMPSC101 FINAL PROJECT";
    string title2 = "CREATED BY: OMEGA9380";

    // Welcome screen:

    system("CLS");

    cout << "/";
    printLine(80);
    cout << "\\" << endl;
    cout << "|" << setw(81) << "|" << endl;
    cout << "|" << setw(41 + (title1.length() / 2)) << title1 << setw(40 - (title1.length() / 2)) << "|" << endl;
    cout << "|" << setw(41 + (title2.length() / 2)) << title2 << setw(40 - (title2.length() / 2)) << "|" << endl;
    cout << "|" << setw(81) << "|" << endl;
    cout << "\\";
    printLine(80);
    cout << "/" << endl;
}

void printLine( int length ) {
    for ( int i = 0; i < length; i++ ) {
        cout << "=";
    }
}

The error is "error: 'printLine' was not declared in this scope". I did declare "printLine()" in the main() function, isn't that enough? Or do I need to declare the function name in every function I plan to use it in? And to answer the burning question, I have to use functions in this final project. Thanks!!!


Solution

  • Assuming you don't really want to have functions declared in main you either need to forward declare welcomeScreen and printLine functions:

    #include <iostream>
    #include <string>
    #include <iomanip>
    using namespace std;
    
    int printLine(int);
    void welcomeScreen();
    
    int main () {
        welcomeScreen();
        return 0;
    }
    
    void welcomeScreen() {
        // definition
    }
    
    void printLine(int length) {
        // definition
    }
    

    or just define them before main:

    #include <iostream>
    #include <string>
    #include <iomanip>
    using namespace std;
    
    int printLine(int length) {
        //definition
    }
    
    void welcomeScreen() {
        // definition
    }
    
    int main () {
        welcomeScreen();
        return 0;
    }