cpp run function that before it is declared? - c++

I'm new to CPP, and I want to know how to run a function that isn't in its scope. I'm used to doing such things in javascript, and I get an error CPP when I try to do that. What I mean is the below:
#include <iostream>
using namespace std;
int tic_h;
int tic_v;
void echo(string e_val){
cout << e_val;
}
void c_mes(){
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
s_v();
}
void s_v(){
echo("Please enter vertical coordinate: ");
cin >> tic_v;
if(tic_v<4&&tic_v>0){
c_mes();
}else{
s_v();
}
}
void s_h(){
echo("Please enter horizontal coordinate: ");
cin >> tic_h;
if(tic_h<4&&tic_h>0){
s_v();
}else{
s_h();
}
}
int main(){
s_h();
return 0;
}
I get this error:
error: 'sv' was not declared in this scope on line 16
How can I make it work?

You should put a function prototype before using the function, for the compiler to know what it is going to be.
Put
void s_v(); // prototype your functions, this is usually done in include files
Right after the #include line.

You'll need to forward declare dostuff, as in the example below.
By doing this you pretty much tell the compiler that the function will be defined else where, but that you'd like to use it.
Excuse the wording, but putting it the way I did is easily comprehensive by a novice programmer.
#include <iostream>
using namespace std;
void dostuff (); // forward declaration
void test(int b){
if(b<11&&b>0){
cout << "Yay!";
}
else{
cout << "The number is not between 1 and 10.";
dostuff();
}
}
void dostuff(){
int numput;
cout << "Please type a number between 1 and 10:";
cin >> numput;
test(numput);
}
int main(){
dostuff();
}
OP just edited the original snippet provided in his question (which the below is a modification off), I'll leave this post the way it is since it explains the situation quite well.

You need to add void s_v(); before the c_mes() function. This is called a function prototype, and it lets the compiler know that that symbol exists and will be implemented later in the code:
#include <iostream>
using namespace std;
int tic_h;
int tic_v;
void s_v();
void echo(string e_val) {
cout << e_val;
}
void c_mes() {
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
s_v();
}
void s_v() {
echo("Please enter vertical coordinate: ");
cin >> tic_v;
if (tic_v < 4 && tic_v > 0) {
c_mes();
} else {
s_v();
}
}
void s_h() {
echo("Please enter horizontal coordinate: ");
cin >> tic_h;
if (tic_h < 4 && tic_h > 0) {
s_v();
} else {
s_h();
}
}
int main() {
s_h();
return 0;
}
Keep in mind that if you ever change the signature for s_v() (that is, add arguments or change the return type), you will need to update the prototype as well.

Declare dostuff somewhere before the void test definitionm e.g on line 3:
void dostuff();
This way you introduce the signature of dostuff function to your program before the function is defined.
In C++ unlike javascript and some other languages, the parser doesn't find all functions then compile the code.

add
void dostuff();
just after the using namespace std; and it will work :)

This is the same error, you use a function before declare it (s_v()), for solve your error you only should create a prototype of s_v():
void s_v(); //at the start of your file

write this
void c_mes(){
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
s_v();
}
after this
void s_h(){
echo("Please enter horizontal coordinate: ");
cin >> tic_h;
if(tic_h<4&&tic_h>0){
s_v();
}else{
s_h();
}
}

Related

Passing a string vector to a function and function prototype issue c++

In this example, the compiler says the function "list" doesn't have a definition, despite me writing one below. If I move the function definition to the top so there is no prototype, it compiles fine.
Can someone explain what's happening here?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void stuff();
void list(vector<string> things);
bool alive = true;
int main()
{
vector<string> things;
things.push_back("Lots");
things.push_back("Of");
things.push_back("Things");
do
{
cout << "What do you want to do?\n\n" << endl;
string input;
cin >> input;
if (input == "stuff")
{
stuff();
}
if (input == "list")
{
list();
}
} while (alive);
return 0;
}
void list()
{
cout << "The things are:\n\n";
for (int i = 0; i < things.size(); ++i)
{
cout << things[i] << endl;
}
}
void stuff()
{
cout << "Some stuff" << endl;
}
Your list function definition signature differs from your function declaration. The function signature should be the same. Your function definition signature should also accept one parameter:
void list(std::vector<string> things)
{
std::cout << "The things are:\n\n";
for (int i = 0; i < things.size(); ++i)
{
std::cout << things[i] << '\n';
}
}
And in your program you call the function with:
list();
where it should be:
list(things);
void list(vector<string> things); is not the same as void list(). You need to actually define your function as void list(vector<string> things) not just the prototype.

Separating a class into cpp and header file (C++)

im new to C++ language.
So I was assigned to split an existing file into three source code: swap.h, swap.cpp and source3.cpp
Existing File:
#include <iostream>
void get_numbers (int&, int&);
void swap_values (int&, int&);
void show_results (int, int);
int main () {
int first_num, second_num;
get_numbers (first_num, second_num);
swap_values (first_num, second_num);
show_results (first_num, second_num);
return 0;
}
void get_numbers (int& input1, int& input2) {
using namespace std;
cout << "Enter two integers: ";
cin >> input1 >> input2;
}
void swap_values (int& variable1, int& variable2) {
int temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
void show_results (int output1, int output2) {
using namespace std;
cout << "In reverse order the numbers are: "
<< output1 << " " << output2 << endl;
}
swap.h contains function prototypes
swap.cpp contains function implementations
source3.cpp contains the main function
for swap.h:
#pragma once
#ifndef swap_h
#define swap_h
void get_numbers(int&, int&);
void swap_values(int&, int&);
void show_results(int, int);
#endif
for swap.cpp
#include <iostream>
void get_numbers(int& input1, int& input2) {
using namespace std;
cout << "Enter two integers: ";
cin >> input1 >> input2;
}
void swap_values(int& variable1, int& variable2) {
int temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
void show_results(int output1, int output2) {
using namespace std;
cout << "In reverse order the numbers are: "
<< output1 << " " << output2 << endl;
}
for source3.cpp:
#include "stdafx.h"
#include "swap.h"
int main()
{
int first_num, second_num;
get_numbers(first_num, second_num);
swap_values(first_num, second_num);
show_results(first_num, second_num);
return 0;
}
When I debug the program, it says: "Unable to start program 'C:\User......'
The system cannot find the file specified. What am I doing wrong?
Since your code compiles successfully, but cannot be started, you probably have problems related to your debugging environment.
Also, you don't need #ifdef, #define, and #endif once you have #pragma once.
If what you provided is the whole code, you didn't include swap.h in swap.cpp. Therefore you have the definition of the functions, but no declaration. Although I would imagine another error or at least a warning here. Try to fix that.
If it doesn't work, try building the Release Version. Does it compile? Does it start? And when it is starting, does it do anything? If what I mentioned before is the problem, I would expect the program to just run to the end, without doing anything.
If the problem lies with swap.h in the main File, make sure it is in the same location, or the include paths point to the directory which contains it. Same goes for stdafx.h
Also, you don't need #pragma once and #ifndef #define and #endif. Get rid of either of those, I recommend using #ifndef #define and #endif, because #pragma once is not supported everywhere. But for you it shouldn't matter.

Programming error in C++

I recently started learning C++ but I came across a problem. The program given below is not giving me the desired result as I only see 'Hi' in the result but not what's written in the void function. Please tell me the reason that this is happening along with the solution.
I am using Xcode 6.3.1 and the I have selected the language C++.
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
void ABC ();
return 0;
}
You are redeclaring a void ABC() function inside main(). Just call ABC(); without the void.
You can take a look at this question about declaring a function within the scope of another.
In your code your function call was wrong.
When you call your function you don't need to add the return type:
#include
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC ();
return 0;
}
you need to call your method and not declare it inside main
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}
EDIT 1:
Since you started learning C++ i recommend the following recommendations to make sure your code is cleaner. Please note , these are not rules by any mean , but more of best practices and a style of coding.
Use meaningful names for your variables, methods, functions , classes
... So instead of ABC() name it something that if you (or someone
else is reading it) will now what it suppose to do.
When calling methods and functions try to declare them with the
appropriate returning value. Void by definition doesn't return any
value it just process the code inside of it. so your methods/function
should return appropriate values of do what it suppose to.
Here's version 2 of your code with examples of 3 different methods and calls:
#include <iostream>
using namespace std;
int sum;
string MethodReturningString()
{
return "Hey there i am the result of a method call !";
}
int MethodReturningInt()
{
return 5;
}
void CalculateSum(int x,int y)
{
sum=x+y;
}
int main()
{
cout << MethodReturningString() << endl;
cout << MethodReturningInt() << endl;
cout << "Calculating sum:" ;
CalculateSum(5,4);
cout << sum << endl;
return 0;
}
Happy coding
In C++, like pretty much any other language, you do not specify the return type when calling a function. So change the line that reads:
void ABC ();
to:
ABC();
Try this:
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC();
return 0;
}
You should call a function simply by stating its name and adding parentheses.
instead of using void ABC() for calling the function ABC() in main(), use the following code:
#include
void ABC ()
{
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}

Understanding Data Structures and Classes C++

So I'm having trouble understanding how Struct works in C++ I have develop a code in which I've been playing for a while but I don't seem to display for the results I'm looking for. I don't get any compiler errors or mistakes so it seems to be running ,This is what I have ...
Question: How do I display the results in "void Save_Player_Name(Player_Data Player)" later on in the future... ?
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
}Customer[1];
int main()
{
Save_Name_File();
}
void Save_Name_File()// will capture the name of the player
{
int n;
int i = 1;// number of players
//cin.get();
for (n=0; n<i; n++)// will the player
{
cout << string(30, '\n');
cout << "Player Amount " << n << " Out of : " << i;
cout << "\n Please enter the name you wish to play \n\n Name: ";
getline (cin,Customer[n].Player_Name);
}
}
void Save_Player_Name(Player_Data Player)// will store the name of the player in a file
{
ofstream scores_data;
scores_data.open ("scores.dat", std::ios_base::app);
cout << Player.Player_Name << endl;
scores_data<< Player.Player_Name << "\n";
scores_data.close();
}
Edit: minor fixes.
Edit: Added class consideration.
Question: How do I display the results in "void
Save_Player_Name(Player_Data Player)" later on in the future... ?
If you are asking how to read the data in from a file:
const bool readFile()
{
ifstream ip;
ip.open("scores.dat", ifstream::in);
if( !ip )
{
printf("Unable to open file.");
return false;
}
// loop over every line in the file
string bffr;
while( getline(ip, bffr) )
{
<do something>
}
}
If you are referring to how to access the data stored in the variable:
Technically, you should be able to do the following from main:
Save_NameFile();
printf("Player name: %s", Customer[n].Player_name.c_str());
However, having Customer be global is bad for a number of reasons. Instead, you should create a local instance in main and pass it to your functions. You will then be able to access it in the same manner.
Note: I used printf instead of cout. I would recommend getting familiar with it. You'll need to include stdio.h, I believe.
Also, you need to make sure you are passing your struct by reference. There are a number of reasons why you should do this, but you will need to in order to get the data back out.
void Save_Player_Name(Player_Data &Player) {<<stuff here>>}
You should also be declaring your functions before main:
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
};
void askUserForName(Player_Data &);
void writeNameToFile(Player_Data &);
void main()
{
Player_Data player;
askUserForName(player);
return;
}
void askUserForName(Player_Data &player)
{
<<do stuff>>
writeNameToFile(player);
return;
}
etc.
Unless you really need to use a struct, I would recommend going with classes. Structs make everything (variables and methods) public by default, whereas classes are private by default. In reality, structs and classes are identical--you can use them fairly interchangeably (don't shoot me!); in practice, structs are generally used when you need to aggregate some data (i.e., variables) without methods.
Your class might end up something like this (I haven't tested it, and I've been coding in Python lately, so please forgive any minor errors):
class PlayerData
{
public:
PlayerData()
{
}
~PlayerData()
{
}
void askUserForName()
{
<<code here>>
}
void writeNameToFile()
{
<<code here>>
// also write to screen
printf("[Write to console] name: %s\n", this->name_.c_str());
}
private:
std::string name_;
};
void main()
{
PlayerData player;
player.askUserForName();
player.writeNametoFile();
return;
}
In reality, you'd want to use a header file and separate things out, but I'll leave that for another day.
You haven't called the method that saves the player after you call Save_Name_File()
You need some logic fixes for your code
#include <iostream>
#include <fstream>
using namespace std;
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
}Customer[1];
void Save_Player_Name(Player_Data Player)// will store the name of the player in a file
{
ofstream scores_data;
scores_data.open ("scores.dat", std::ios_base::app);
cout << Player.Player_Name << endl;
scores_data<< Player.Player_Name << "\n";
scores_data.close();
}
void Save_Name_File()// will capture the name of the player
{
int n;
int i = 1;// number of players
//cin.get();
for (n=0; n<i; n++)// will the player
{
cout << "Player Amount " << n << " Out of : " << i;
cout << "\n Please enter the name you wish to play \n\n Name: ";
getline (cin,Customer[n].Player_Name);
Save_Player_Name(Customer[n]);
}
}
int main()
{
Save_Name_File();
return 0;
}

C++ Inheritance problem

I hope I got the relevant code in here. I have some problem when I want to fetch the menu option that I've added into to menu_1. I have this function on_select(int) that I use to fetch one sub-menu's options, which I do by using the display() function. But when I compile it will say that there are no function named display() in menu_option() class, which is the Base class, but what I want to is to access the display() function which is located in the sub_menu() class.
I have tried multiple thing to get the relevant object from the array without any success, so I'm here now asking for help with this one.
I have this following main()
#include <iostream>
using namespace std;
#include "menu.h"
int main()
{
sub_menu* main_menu = new sub_menu("Warehouse Store Menu");
sub_menu* menu_1 = new sub_menu("Menu1");
main_menu->add_option(new sub_menu("Menu2"));
main_menu->add_option(menu_1);
product_menu->add_option(new add_item("sub_item1"));
product_menu->add_option(new add_item("sub_item2"));
product_menu->add_option(new add_item("sub_item3"));
main_menu->display();
main_menu->on_select(1);
delete main_menu;
return 0;
}
header file
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
const int MAX_SIZE = 9;
class menu_option
{
public:
menu_option(string const& n) : title(n) {};
virtual ~menu_option();
virtual void on_select(int) = 0;
string get_title() { return title; }
protected:
string title;
};
/* ------------------------------------- */
class sub_menu : public menu_option
{
public:
sub_menu(string const& n)
: menu_option(n) { no_item = 0; }
~sub_menu() { delete[] list; };
void on_select(int);
void add_option(menu_option*);
void display();
private:
menu_option* list[MAX_SIZE]; //container for options in the sub_menu
int no_item;
};
implement file
void sub_menu::on_select(int i)
{
cout << (list[i])->get_title() << endl;
cout << (list[i])->display() << endl; //<------ Doesn't work
}
void sub_menu::add_option(menu_option* item)
{
list[no_item] = item;
no_item++;
}
void sub_menu::display()
{
cout << ">> " << get_title() << " <<"<< endl;
for( int i = 0; i < no_item; i++ )
{
cout << setw(2) << i << ": " << (list[i])->get_title() << endl;
}
}
You can do what you want to do, but it's bad. You have to cast down to sub_menu when you call display() in on_select(). Of course it's not going to work the way you have it, and the compiler is telling you exactly why.
The other option, which is probably better (though without a clear understanding of the problem space may not be the best) would be to add display() as a virtual function to the menu_option class.
To solve your immediate problem you'll want to use dynamic_cast to turn a menu_option* into a sub_menu*, like so:
sub_menu* submenu(dynamic_cast<sub_menu*>(list[i]));
Note that if the cast fails (i.e., the menu_option pointed to by list[i] is not a sub_menu after all) the value of the submenu pointer will be NULL, so make sure you check that it is a valid pointer before using it in subsequent code.