当我将它们保存在str()
文件中时,所有这些功能都可以工作,但是现在我将它们移到了头文件中。
这是我的main.cpp
:
general_functions.cpp
这是#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include "general_functions.hpp"
using namespace std;
bool check_if_room_exists(int room_number){
string room_number_full = to_string(room_number) + ".txt";
ifstream new_file;
new_file.open(room_number_full);
if(new_file.is_open()){
return true;
}else{
return false;
}
}
int get_new_room_number(){
int room_number;
cout<<"What room number do you want this room to have?"<<endl;
cout<<"Enter your choice: ";
cin>>room_number;
while(!room_number || check_if_room_exists(room_number) == true){
// Taken from StackOverflow to avoid endless loop: https://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a-number
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// End of code taken from StackOverflow
if(check_if_room_exists(room_number) == true){
cout<<"A room with that number already exists.\nEnter your new choice: ";
}else{
cout<<"Please ensure you enter only numeric values for the room number.\nEnter your new choice: ";
}
cin>>room_number;
}
return room_number;
};
int get_cost_per_night(){
int cost;
cout<<"Please enter the cost per night for this room: ";
cin >> cost;
while(!cost || cost < 1){
// Taken from StackOverflow to avoid endless loop: https://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a-number
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// End of code taken from StackOverflow
if(!cost){
cout<<"Please ensure you enter only numeric values for the cost per night.\nEnter your new choice: ";
}else{
cout<<"The price is less than £0. Please enter a value above £0: ";
}
cin>>cost;
}
return cost;
}
int get_room_number(){
int room_number;
cout<<"Please enter the room number you wish to view: ";
cin >> room_number;
while(check_if_room_exists(room_number) == false){
// Taken from StackOverflow to avoid endless loop: https://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a-number
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// End of code taken from StackOverflow
if(check_if_room_exists(room_number) == false){
cout<<"That room doesn't exist enter a new one: ";
}
cin>>room_number;
}
return room_number;
}
void delete_room(int room_number){
remove((to_string(room_number) + ".txt").c_str());
}
文件:
general_functions.hpp
最后,这就是我将头文件导入到我的#ifndef general_functions_hpp
#define general_functions_hpp
#include <stdio.h>
using namespace std;
bool check_if_room_exists(int);
int get_new_room_number();
int get_cost_per_night();
int get_room_number();
void delete_room(int);
#endif
文件中的方式:
main.cpp
这会导致出现以下错误:
#include "general_functions.hpp"
根据我所做的研究,我认为这是由于函数的定义与实际不匹配而引起的,但是从我的观察中可以看出,它们匹配并且不会引起任何问题。
我们将不胜感激!
谢谢