c++ put functions in separate source files - c++

Currently I have an unique source file (*.cpp) where all my functions are working right. Now i'm trying to take some of them out into separate source files and including them into main source with no success.
My current project is as follows:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
using namespace std;
using std::cout;
using std::ifstream;
/*This is one of the functions to be put in separate file:*/
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
bool MisionCumplida = false;
bool EncabezadoListo = false;
int i = 0;
int j = 0;
char * pch;
char istr[256];
const int NUM_DATA = 15;
static string data[NUM_DATA];
std::stringstream InputString;
ifstream inputFile(RutayNombre);
if (inputFile.is_open())
{
while (inputFile.good() && MisionCumplida == false)
{
i = 0;
inputFile.getline(istr,256);
pch = strtok (istr,":");
if (string(pch) == "[Pagina]")
{
EncabezadoListo = true;
}
else
{
EncabezadoListo = false;
}
if (string(pch) == Page)
{
MisionCumplida = true;
}
while (pch != NULL)
{
if ((EncabezadoListo == true) || (MisionCumplida == true))
{
data[i] = data[i] + " " + string(pch);
}
pch = strtok (NULL, ",");
i++;
}
}
inputFile.close();
return data;
}
} //End of function 'ReadPageAsignations'
/*This is another function where my function "ReadPageAsignations' get called -- btw, I want also this function to be in a separate source file.*/
void DeliverHtml (const char* page){//const char* RutayNombre ) {
string *p;
char * pch;
size_t pos;
string RutayNombre;
RutayNombre = "../Substructure/Templates/" + SearchConfigValue( "../Substructure/Conf/Config-Templates.txt", "htmlTemplate:");
const char *RutayNombreConfigCompos = "../Substructure/Conf/Config-Composition.txt";
string RutayNombreParaInsertar;
string token, token1, token2;
string line, lineRead, lineToInsert;
char * StrToTokenize2;
string StrToTokenize1;
p=ReadPageAsignations( RutayNombreConfigCompos, page); //Here, I call the function I want in a separate file
...
}
/*And here is the main() function*/
int main()
{
char *value = "page=Home";
if (NULL!=strstr(getenv("QUERY_STRING"), "page="))
{
value = getenv("QUERY_STRING");
}
char *posCh = strstr(value, "=");
DeliverHtml(&posCh[0]+1);
return 0;
}
For the first function, I have tried creating the header file 'ReadPageAsignations.h' and a source file 'ReadPageAsignations.cpp'.
Header file 'ReadPageAsignations.h' containing:
#ifndef READPAGEASIGNATIONS_H_INCLUDED
#define READPAGEASIGNATIONS_H_INCLUDED
string *ReadPageAsignations ( const char* RutayNombre, const char* Page );
#endif // READPAGEASSIGNATIONS_H_INCLUDED
Source file 'ReadPageAsignations.cpp' for separate function containing:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
using std::cout;
using std::ifstream;
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
bool MisionCumplida = false;
bool EncabezadoListo = false;
int i = 0;
int j = 0;
char * pch;
char istr[256];
const int NUM_DATA = 15; /*El numero de elementos debe coincidir con el iterador en la función Deliverhtml.*/
static string data[NUM_DATA];
std::stringstream InputString;
ifstream inputFile(RutayNombre); //Abre el archivo y lo asigna al stream inputFile.
if (inputFile.is_open()) //Chequea que el archivo esté abierto.
{
while (inputFile.good() && MisionCumplida == false)
{
i = 0;
inputFile.getline(istr,256);
pch = strtok (istr,":");
if (string(pch) == "[Pagina]")
{
EncabezadoListo = true;
}
else
{
EncabezadoListo = false;
}
if (string(pch) == Page)
{
MisionCumplida = true;
}
while (pch != NULL)
{
if ((EncabezadoListo == true) || (MisionCumplida == true))
{
data[i] = data[i] + " " + string(pch);
}
pch = strtok (NULL, ",");
i++;
}
}
inputFile.close();
return data;
}
} //End function
and, main project containing:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
#include "ReadPageAsignations.h" //Here I #include the function definition file (header)
using namespace std;
using std::cout;
using std::ifstream;
...
}
I've got a lot of compiling errors:
\ReadPageAsignations.h|4|error C2143: syntax error : missing ';' before '*'|
\ReadPageAsignations.h|4|error C4430: missing type specifier - int assumed. Note: C++ does not support default-int|
\ReadPageAsignations.h|4|error C4430: missing type specifier - int assumed. Note: C++ does not support default-int|
main.cpp|20|error C2872: 'string' : ambiguous symbol|
...
I'm working Code::blocks 13.12 with MS Visual C++ 2005/2008 compiler.
any help will be highly appreciated, thanks in advance.

The error is telling you that when it tried to parse the header file it encountered the symbol string and doesn't recognize it. Adding #include <string> to your header file and fully qualifying the string type as std::string should correct the problem.

You should put #include <string> in your header file and remove it from your .cpp file
as following:
main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
#include "ReadPageAsignations.h"
...
note: including header file with the same name of .cpp file , include both.
ReadPageAsignations.h
#ifndef READPAGEASIGNATIONS_H_INCLUDED
#define READPAGEASIGNATIONS_H_INCLUDED
#include <string> //<-----This line, include string header
std::string *ReadPageAsignations ( const char* RutayNombre, const char* Page );
#endif // READPAGEASSIGNATIONS_H_INCLUDED
ReadPageAsignations.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include "ReadPageAsignations.h" // <--- add the header file here
//#include <string> <---remove it already included in the header file
using namespace std;
//using std::cout; <--remove this you already used namespace std
//using std::ifstream; <--remove this you already used namespace std
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
... } //End function

Related

My application name changes after runtime, but it has no file extension, I want it to be in .exe

My application name changes after runtime, but it has no file extension. I want it to be an .exe.
I'm new to c++ and I really need to figure this out.
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
using namespace std;
std::string path()
{
char shitter[_MAX_PATH]; // defining the path
GetModuleFileNameA(NULL, shitter, _MAX_PATH); // getting the path
return std::string(shitter); //returning the path
}
int main()
{
srand(time(NULL));
char letter = 'A' + (rand() % 26);
const char *val = new char(letter);
std::rename(path().c_str(), val); //renaming the file
}
I tried doing this
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
using namespace std;
std::string path()
{
char shitter[_MAX_PATH]; // defining the path
GetModuleFileNameA(NULL, shitter, _MAX_PATH); // getting the path
return std::string(shitter); //returning the path
}
int main() {
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); // Higher Priority
SetConsole();
srand(time(NULL));
char letters = 'A'+ (rand() % 26);
const char* val = new char(letters);
std::string rename(path().c_str(), val += ".exe"); //renaming the file
But now im getting an error
https://prnt.sc/uejlxz
rename(path().c_str(), val + ".exe")
or use append
String Concatenation

"extern vector<string> startParsing(FILE*);"

I'm learning C++, and I have the following problem. I can't understand how this sentence interacts
extern vector<string> startParsing(FILE*);
I tried to find information about (FILE*) but I can't find anything.
main.cpp
#include <iostream>
#include <fstream>
#include "Parser/parser.h"
using namespace std;
int main(int argc, char** argv)
{
cout<<"Welcome to Group 01 final project."<<endl;
std::string rule_file = "urbanmodel.zoo";
// parsing
Parser parser(rule_file);
std::vector<std::string> tokens = parser.parse();
parser.printTokens();
return 1;
}
parser.cpp
#include "parser.h"
extern vector<string> startParsing(FILE*); //<---------------------???
Parser::Parser(string filePath){
// open a file handle to a particular file:
this->myfile = fopen(filePath.c_str(), "r");
// make sure it's valid:
if (!this->myfile) {
cout << "I can't open the urbanmodel.zoo file!" << endl;
}
};
vector<string> Parser::parse(){
if(this->myfile)
this->tokens = startParsing(myfile);
return this->tokens;
};
void Parser::printTokens(){
int size = this->tokens.size();
for(int i=0;i<size;i++)
cout<<this->tokens[i];
cout<<std::endl;
};
parser.h
#include <iostream>
#include <vector>
#include <cstdio>
#include "scanner.h"
using namespace std;
class Parser{
private:
FILE* myfile; //<----------------------------------------???
vector<string> tokens;
public:
Parser(string filePath);
vector<string> parse();
void printTokens();
};

Ambiguous pointer; <SiHCollection> is ambiguous

below I've posted my code which is meant to store hits collections in HCE (hit collection of events).
The code compiles successfully but on running the program, the following error is printed to the terminal seven times:
< SiHCollection> is ambiguous.
I have a feeling it is because I am using namespace std although I don't know how to amend the code. Any thoughts?
#include "SiSD.h"
#include "SiHit.h"
#include "G4HCofThisEvent.hh"
#include "G4Step.hh"
#include "G4ThreeVector.hh"
#include "G4SDManager.hh"
#include "G4ios.hh"
#include "G4UnitsTable.hh"
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
extern ofstream outfile;
SiSD::SiSD(G4String name)
:G4VSensitiveDetector(name)
{
collectionName.insert("SiHCollection");
}
SiSD::~SiSD(){ }
void SiSD::Initialize(G4HCofThisEvent* HCE)
{
SiHCollection = new SiHitsCollection(SensitiveDetectorName,
collectionName[0]);
static G4int HCID = -1;
if(HCID<0)
{
HCID = G4SDManager::GetSDMpointer()->GetCollectionID(collectionName[0]);
}
HCE->AddHitsCollection(HCID, SiHCollection);
}
G4bool SiSD::ProcessHits(G4Step* aStep, G4TouchableHistory*)
{
if(aStep->GetTrack()->GetTrackID() > 0) {
G4double edep = aStep->GetTotalEnergyDeposit();
if(edep==0) return false;
SiHit* aHit = new SiHit();
aHit->SetEdep(edep);
SiHCollection->insert(aHit);
return true;
} else return false;
}

howto: Read input and store it in another file

I want to make a program that reads the highest value from one file and stores it in another. I've read about ifstream and ofstream but how do I let the ofstream store the highest value from the instream in another file? Here is what I have so far:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
struct CsvWhitespace : ctype<char> {
static const mask* make_table() {
static vector<mask> v{classic_table(), classic_table() + table_size};
v[','] |= space; // comma will be classified as whitespace
return v.data();
}
CsvWhitespace(size_t refs = 0) : ctype{make_table(), false, refs} {}
} csvWhitespace;
int main() {
string line;
ifstream myfile ("C:/Users/Username/Desktop/log.csv");
ofstream myfile2 ("C:/Users/Username/Desktop/log2.csv");
return 0;
}
auto v = vector<int>{};
myfile.imbue(locale{myfile.getloc(), &csvWhitespace});
copy(istream_iterator<int>{myfile}, istream_iterator<int>{}, back_inserter(v));
myfile2 << *max_element(begin(v), end(v));
}
Thanks in advance :)
You could just copy from the one file in the other, without having to worry about the format, by treating them in binary mode. Here is an example:
#include <stdio.h>
#include <string.h>
#define bufSize 1024
int main(int argc, char *argv[])
{
FILE *ifp, *ofp;
char buf[bufSize];
if (argc != 3)
{
fprintf(stderr,
"Usage: %s <soure-file> <target-file>\n", argv[0]);
return 1;
}
if ((ifp = fopen(argv[1], "rb")) == NULL)
{ /* Open source file. */
perror("fopen source-file");
return 1;
}
if ((ofp = fopen(argv[2], "wb")) == NULL)
{ /* Open target file. */
perror("fopen target-file");
return 1;
}
while (fgets(buf, sizeof(buf), ifp) != NULL)
{ /* While we don't reach the end of source. */
/* Read characters from source file to fill buffer. */
/* Write characters read to target file. */
fwrite(buf, sizeof(char), strlen(buf), ofp);
}
fclose(ifp);
fclose(ofp);
return 0;
}
which was given as an example in IP, source. You just need to specify the cmd arguments as the desired files.
You can do it like this. Live example using cin and cout rather than files.
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
struct CsvWhitespace : ctype<char> {
static const mask* make_table() {
static vector<mask> v{classic_table(), classic_table() + table_size};
v[','] |= space; // comma will be classified as whitespace
return v.data();
}
CsvWhitespace(size_t refs = 0) : ctype{make_table(), false, refs} {}
};
int main() {
string line;
ifstream myfile("log.csv");
ofstream myfile2("log2.csv");
auto v = vector<int>{};
myfile.imbue(locale{myfile.getloc(), new CsvWhitespace{}});
copy(istream_iterator<int>{myfile}, istream_iterator<int>{}, back_inserter(v));
myfile2 << *max_element(begin(v), end(v));
}

vector<wstring> as Return value and Parameter

I want to create some modules for my program. I want to call a function and pass a vector as a parameter. The return value should also be a vector.
My code looks like this
main.cpp
//BlueSmart.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
using namespace std;
#pragma comment(lib, "Irprops.lib")
BLUETOOTH_FIND_RADIO_PARAMS m_bt_find_radio = {
sizeof(BLUETOOTH_FIND_RADIO_PARAMS)
};
BLUETOOTH_RADIO_INFO m_bt_info = {
sizeof(BLUETOOTH_RADIO_INFO),
0,
};
BLUETOOTH_DEVICE_SEARCH_PARAMS m_search_params = {
sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS),
1,
0,
1,
1,
1,
15,
NULL
};
BLUETOOTH_DEVICE_INFO m_device_info = {
sizeof(BLUETOOTH_DEVICE_INFO),
0,
};
HANDLE m_radio = NULL;
HBLUETOOTH_RADIO_FIND m_bt = NULL;
HBLUETOOTH_DEVICE_FIND m_bt_dev = NULL;
int wmain(int argc, wchar_t **args) {
while(true) {
m_bt = BluetoothFindFirstRadio(&m_bt_find_radio, &m_radio);
do {
localBluetoothDevices ();
m_search_params.hRadio = m_radio;
::ZeroMemory(&m_device_info, sizeof(BLUETOOTH_DEVICE_INFO));
m_device_info.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
m_bt_dev = BluetoothFindFirstDevice(&m_search_params, &m_device_info);
vector<wstring> vec;
int m_device_id = 0;
do {
wostringstream tmp;
++m_device_id;
//Something like this <----------------------------------------
externBluetoothDevices (vec);
//Something like this <----------------------------------------
wprintf(L"********************************************************************** \n");
wprintf(L"\tDevice %d:\r\n", m_device_id);
wprintf(L"\t\tName: %s\r\n", m_device_info.szName);
wprintf(L"\t\tAddress: %02x:%02x:%02x:%02x:%02x:%02x\r\n", m_device_info.Address.rgBytes[0], m_device_info.Address.rgBytes[1], m_device_info.Address.rgBytes[2], m_device_info.Address.rgBytes[3], m_device_info.Address.rgBytes[4], m_device_info.Address.rgBytes[5]);
wprintf(L"====================================================================== \n");
for (int i = 0; i < 6; i++) {
tmp << hex << m_device_info.Address.rgBytes [i];
if (i < 5)
tmp << L':';
}
vec.push_back(tmp.str());
} while(BluetoothFindNextDevice(m_bt_dev, &m_device_info));
BluetoothFindDeviceClose(m_bt_dev);
//Sleep(10*1000*60);
Sleep(10000);
} while(BluetoothFindNextRadio(&m_bt_find_radio, &m_radio));
BluetoothFindRadioClose(m_bt);
}
return 0;
}
//Lokal verfügbare bzw. angeschlossene Bluetooth-Devices
void localBluetoothDevices (){
int m_radio_id = 0;
m_radio_id++;
BluetoothGetRadioInfo(m_radio, &m_bt_info);
//Lokaler Bluetoothadapter
wprintf(L"====================================================================== \n");
wprintf(L"Local Device Nr. %d\n", m_radio_id);
wprintf(L"\tName: %s\r\n", m_bt_info.szName);
wprintf(L"\tAddress: %02x:%02x:%02x:%02x:%02x:%02x\r\n", m_bt_info.address.rgBytes[0], m_bt_info.address.rgBytes[1], m_bt_info.address.rgBytes[2], m_bt_info.address.rgBytes[3], m_bt_info.address.rgBytes[4], m_bt_info.address.rgBytes[5]);
}
//Extern verfügbare bzw. Bluetooth-Devices
vector<wstring> externBluetoothDevices (vector<wstring> &vec){
return vec;
}
stdafx.h
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <winsock2.h>
#include <windows.h>
#include <stdlib.h>
#include <bthdef.h>
#include <BluetoothAPIs.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
#include <iomanip>
#include <conio.h>
void localBluetoothDevices ();
vector<wstring> externBluetoothDevices (vector<wstring>);
It says that vector is not a known type. What am I doing wrong?
In stdafx.h replace
vector<wstring> externBluetoothDevices (vector<wstring>);
with
std::vector<std::wstring> externBluetoothDevices (std::vector<std::wstring>);
Basically the issue was although you put using namespace std; in your cpp file that doesn't count in your header file which is before the using declaration is seen.
Also note that your defintion in the cpp file is different. In the cpp file you have a reference
vector<wstring> externBluetoothDevices (vector<wstring>&);
Decide which you really want.
You should pass a pointer of a vector.