I have following program to access sqlite database and to get the content of a table into a LIST CONTAINER.
All I want is to print the data which is in the list container.But I get this ERROR.
error: expected primary-expression before ‘<<’ token
The below file is DBAccess1.cpp
#include <iostream>
#include <sqlite3.h>
#include <list>
#include <iterator>
#include <algorithm>
#include <string>
#include <cstring>
#include <sstream>
#include "DBAccess1.h"
bool sqliteDB::GET_ALL_Site_Code(list<SiteCode>& Site_Code_list)
{
sqlite3 *db;
const char *sql;
sqlite3_stmt * stmt;
int rc = sqlite3_open("/DBsqlite3/empdbv3.db", &db);
sql = "SELECT * FROM SiteCode;";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
while(sqlite3_step(stmt)==SQLITE_ROW) {
int column = sqlite3_column_count(stmt);
for(int i = 0; i < column; i++)
{
int A = sqlite3_column_int(stmt, 0);
int B = sqlite3_column_int(stmt, 1);
SiteCode info;
info.siteID = A;
info.siteCode = B;
cout<<"Preparing to push data into List"<<endl;
Site_Code_list.push_back(info);
cout<<"Data was pushed successfully"<<endl;
}//FOR LOOP ENDS HERE
}// WHILE LOOP ENDS HERE
sqlite3_finalize(stmt);
sqlite3_close(db);
return true;
}
//=================================XX=============================//
void sqliteDB::printList()
{
int s = Site_Code_list.size();
cout << "The size of List is :" << s << endl;
for( list<SiteCode> :: iterator it = Site_Code_list.begin(); it != Site_Code_list.end(); it++)
cout << it* << " "; //The ERROR occurs here
}
Below is my DBAccess.h file:
#ifndef DBAccess1_HH
#define DBAccess1_HH
#include <iostream>
#include <sqlite3.h>
#include <list>
#include <iterator>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <string>
using namespace std;
struct SiteCode
{
int siteID;
int siteCode;
};
class sqliteDB {
public:
list<SiteCode> Site_Code_list;
bool GET_ALL_Site_Code(list<SiteCode>& Site_Code_list);
void printList();
};
#endif
And below is my main.cpp from where I am calling the functions:
int main()
{
sqliteDB object1;
list<SiteCode> Site_Code_list;
object1.GET_ALL_Site_Code(Site_Code_list);
object1.printList();
cout << "\n\nAll the statement were executed properly\n\n";
return 0;
}
The Error I get is:
error: expected primary-expression before ‘<<’ token
cout << it* << " ";
You have two "errors" in your code. The first is the one that everyone else has pointed out. This
cout << it * << " ";
should be this
cout << *it << " ";
Which if course generates the second error
no match for ‘operator<<’ (operand types are ‘std::ostream
{aka std::basic_ostream<char>}’ and ‘SiteCode’)
std::cout << *it << " ";
Which is actually telling you exactly what the problem is. You are trying to output a SiteCode object onto the stream, but there is no << operator defined for a SiteCode object.
You need to add the following for your SiteCode struct.
ostream& operator<< (ostream &out, SiteCode &site)
{
out << "(" << site.siteID << "," << site.siteCode << ")";
return out;
}
Declare this in the header file, after the struct is defined, thus:
struct SiteCode
{
int siteID;
int siteCode;
};
inline ostream& operator<< (ostream &out, SiteCode &site)
{
out << "(" << site.siteID << "," << site.siteCode << ")";
return out;
}
And now you will be able to use << with any SiteCode object on any stream.
How you actually format the output of the object is up to you. I just chose to display it as a tuple.
Introduction
Dereferencing an iterator is done with *it, not it* - the latter would expect another operand; "multiplication of it and primary-expression".
cout << *it << " "; // fixed
Note
The previous "fix" will require you to define a operator<< suitable for std::cout, and an object of type SiteCode.
If you just want to print the list in a simple manner you can do the following:
cout << it->siteID << " " << it->siteCode << "\n";
Related
Context
My professor gave me a task to make a program using aggregation between 2 classes while also separating the classes into a .h and .cpp files.
My solution
The header file containing the class declaration:
#include <iostream>
#include <string>
using namespace std;
class medicalCompany {
private:
string ceoName;
string email;
string phoneNumber;
string locate;
public:
medicalCompany();
void Name(string n);
void mail(string m);
void phone(string p);
void location(string l);
~medicalCompany();
};
class origin {
private:
medicalCompany country;
public:
origin();
void address();
~origin();
};
and my .cpp file:
#include <iostream>
#include "function.h"
#include <string>
using namespace std;
medicalCompany::medicalCompany() {
cout << "OUR COMPANY IS GLAD TO BE OF SERVICE !" << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::Name(string n){
ceoName = n;
cout << "OUR CEO IS " << endl;
cout<< ceoName << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::mail(string m) {
email = m;
cout << "USE OUR EMAIL TO CONTACT US : " << endl;
cout<< email << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::phone(string p) {
phoneNumber = p;
cout << "THIS IS OUR CUSTOMER SERVICE PHONE NUMBER " << endl;
cout<< phoneNumber << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::location(string l) {
locate = l;
cout << " OUR COMPANY IS LOCATED IN " << endl;
cout << locate << endl;
cout << "****************************************************" << endl;
}
medicalCompany::~medicalCompany() {
cout << "thanks for trusting our company ^_^" << endl;
cout << "****************************************************" << endl;
}
origin::origin() {
cout<< "constructor 2"<<endl;
}
void origin::address() {
cout << country.location;
}
origin::~origin() {
cout << "bye" << endl;
}
The two classes are used in my main.cpp file:
#include <iostream>
#include <string>
#include "function.h"
using namespace std;
int main() {
medicalCompany o;
o.Name("jack");
o.mail("ouremail#company.com");
o.phone("2342352134");
o.location("Germany");
origin o2;
return 0;
}
Problem
I run into this error :
Severity Code Description Project File Line Suppression State
Error C3867 'medicalCompany::location': non-standard syntax; use '&' to create a pointer to member CP2_HW c:\function.cpp 41
You can either:
replace void origin::address(){cout << country.location;} by void origin::address(){country.location();}
or by void origin::address(){cout << country.locate;} if you put the locate member as a public variable.
Also, few remarks:
Generally you would prefer avoiding exposing private members, so the first solution should be prefered.
the instruction using namespace std; is usually considered bad practice, and should be avoided, as the cost of possible risks does not overweight the benefit of not having to type std::cout(see this question for more information)
In terms of naming convention, I would have exchanged the names of locate and location: location should be the member variable and locate the action (function) of getting the location.
Prefer using a constructor and intialization lists rather than getter/setter.
Your output formatting should be very separate from the logic of your classes, for example implementing a << operator for your class.
Following this logic, your code should look more like:
#include <iostream>
#include <string>
class medicalCompany {
private:
std::string _ceoName;
std::string _email;
std::string _phoneNumber;
std::string _location;
public:
// Constructor
medicalCompany(std::string name, std::string email, std::string phone, std::string location):
_ceoName(name),
_email(email),
_phoneNumber(phone),
_location(location)
{}
friend ostream& operator<<(ostream& os, const medicalCompany& dt);
};
and for the ostream operator:
ostream& operator<<(ostream& os, const medicalCompany& co)
{
os << co._ceoName << " " co._phoneNumber << ' ' << co._email;
return os;
}
This would allows to write code like this in your main:
int main() {
medicalCompany o("jack", "ouremail#company.com","2342352134","Germany")
std::cout << o << std::endl;
return 0;
}
The code is not functional and you would have to edit it to fit your formating requirement, but you have the idea :) Good luck!
Here is the code:
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
string sidelength;
cout << "Perimeter of Square" << endl;
cout << "Enter length of one side: ";
getline(cin, sidelength);
cout << sidelength * 4 << endl;
return 0;
}
When run, this is the error message:
error: no match for 'operator*' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'int')|
How do I fix this error and make the program run correctly?
The get line function takes a string as it's second parameter, but you want to get an integer/double/float as an input. So don't use getline. Simply run this code below and it will solve your problem.
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int sidelength;
cout << "Perimeter of Square" << endl;
cout << "Enter length of one side: ";
cin >> sidelength;
cout << sidelength * 4 << endl;
return 0;
}
If you really want to multiply a string by a number, you can overload operator*:
#include <cmath>
#include <iostream>
#include <cctype>
#include <string>
std::string operator*(const std::string &s,int x) {
std::string result;
try {
result = std::to_string(stoi(s)*x);
} catch(const std::invalid_argument&) {
result="UND";
}
return result;
}
std::string operator*(const std::string &s,double x) {
std::string result;
try {
result = std::to_string(stof(s)*x);
} catch(const std::invalid_argument&) {
result="UND";
}
return result;
}
int main()
{
std::string input("1");
input = input * 5.32;
std::cout << input << std::endl;
input = input * 2;
std::cout << input << std::endl;
return 0;
}
I am trying to overload a << operator, but I am having weird problem. More precisely there is error:
Invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'Team')
where Team is my class name.
However my friend checked my code and he said that it's working for him. I am coding using Xcode on Mac.
I suppose that it's something with the compiler, isn't it?
That's my code divided into main, .hpp file and .cpp file:
#include <stdio.h>
#include <iostream>
#include "team.hpp"
int main()
{
Team Legia = {"Legia Warszawa", "Warszawa", 283.5, 2, 42};
Team Jagiellonia = {"Jagiellonia Bialystok", "Bialystok", 34.4, 1, 45};
Legia.print();
Jagiellonia.print();
cout << Legia;
cout << Jagiellonia;
return 0;
}
.hpp file
#include <stdio.h>
#include <iostream>
using namespace std;
class Team {
private:
char *name;
char *location;
double budget;
int place;
int points;
public:
Team();
Team(const char*, const char*, double, int, int);
friend ostream& operator<<(ostream& out, const Team &team);
};
.cpp file
#include "team.hpp"
#include <iostream>
#include <string.h>
using namespace std;
Team::Team(const char *_name, const char *_location, double _budget, int _place, int _points)
{
name = new char[strlen(_name)+1];
strcpy(name, _name);
location = new char[strlen(_location)+1];
strcpy(location, _location);
budget = _budget;
place = _place;
points = _points;
}
Team::Team()
{
name = new char[4];
location = new char[8];
strcpy(name, "name");
strcpy(location, "location");
budget = 0;
place = 0;
points = 0;
}
ostream& operator<<(ostream& out, const Team &team)
{
out << "Informations about " << team.name << ": " << endl
<< "Location: " << team.location << endl
<< "Budget: " << team.budget << " millions (PLN)" << endl
<< "Place: " << team.place << endl
<< "Points: " << team.points << endl << endl;
return out;
}
The whole code without formatting:
http://coliru.stacked-crooked.com/a/7f0681a380324222
#include <string>
#include <iostream>
#include <map>
#include <utility>
using namespace std;
int main()
{
map<int, string> Employees;
// 1) Assignment using array index notation
Employees[5234] = "Mike C.";
Employees[3374] = "Charlie M.";
Employees[1923] = "David D.";
Employees[7582] = "John A.";
Employees[5328] = "Peter Q.";
cout << Employees;
cout << "Employees[3374]=" << Employees[3374] << endl << endl;
cout << "Map size: " << Employees.size() << endl;
/*for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii)
{
cout << (*ii).first << ": " << (*ii).second << endl;
}*/
system("pause");
}
I would like to know what to add in order for me to print cout << Employees; instead of using iterator.Because I did see some code can directly print the map content with just the simple cout << Anythg.I wonder what has made the code work?
Nop, or at least the standard library doesn't provide a default implementation of operator << for container and std::ostream.
Check out https://github.com/louisdx/cxx-prettyprint or write your own implementation of operator<<(std::ostream &, const std::map<T1, T2> &).
Here is simple implemenation, for the sake of example:
#include <map>
#include <string>
#include <iostream>
template<typename T1, typename T2>
std::ostream &operator<<(std::ostream &stream, const std::map<T1, T2>& map)
{
for (typename std::map<T1, T2>::const_iterator it = map.begin();
it != map.end();
++it)
{
stream << (*it).first << " --> " << (*it).second << std::endl;
}
return stream;
}
int main(int, char **)
{
std::map<std::string, int> bla;
bla["one"] = 1;
bla["two"] = 2;
std::cout << bla << std::endl;
return (0);
}
These are the errors that have occured when trying to compile the file main.cpp:
C:\Users\student\Desktop\C++ Solution Framework (1)\AssignmentSolution\AssignmentSolution\main.o:main.cpp|| undefined reference to `MsgPacket::MsgPacket(int, int, int, int, std::string)'|
C:\Users\student\Desktop\C++ Solution Framework (1)\Assignment Solution\AssignmentSolution\main.o:main.cpp|| undefined reference to `DataStream::DataStream()'|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 1 seconds) ===|
This is the main.cpp file itself:
#include <iostream>
#include <iomanip>
#include "DataStream.h"
#include "MsgPacket.h"
using namespace std;
DataStream * Packet = new DataStream();
DataStream::DataStream();
int main() {
int source;
int destination;
int type;
int port;
int input;
std::string data;
cout << "My Assignment" << endl;;
MsgPacket * Packet = new MsgPacket(source,destination,type,port,data);
}
This is the MsgPacket.h
#ifndef MSGPACKET_H
#define MSGPACKET_H
#include <string>
#include "PacketAddress.h"
using namespace std;
class MsgPacket : public PacketAddress {
public:
MsgPacket();
MsgPacket (const MsgPacket & rhs);
MsgPacket(string dataIn);
MsgPacket(int source, int destination, int port, int type, std::string data);
MsgPacket(int ,char data);
string toString();
string getData() const {return _data;};
void setData(string inData) {_data = inData;};
string dataOutput();
virtual ~MsgPacket();
virtual MsgPacket * Clone() { return new MsgPacket(*this); }
protected:
string _data;
};
#endif // MSGPACKET_H
And finally this is the MsgPacket.cpp
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include "msgpacket.h"
using namespace std;
MsgPacket::MsgPacket():
PacketAddress(0,0)
{
}
MsgPacket::MsgPacket (const MsgPacket & rhs):
PacketAddress(rhs),
_data(rhs.getData())
{
}
MsgPacket::MsgPacket(string dataIn):
PacketAddress(0,0){
string temp;
temp = dataIn.substr (0,4);
_source = atoi(temp.c_str());
temp = dataIn.substr (5,4);
_dest = atoi(temp.c_str());
temp = dataIn.substr (10,4);
_type = atoi(temp.c_str());
temp = dataIn.substr (15,4);
_port = atoi(temp.c_str());
_data = dataIn.substr (20,dataIn.length());
#ifdef DEBUG
cout << "CREATE PACKET: " << this->toString() << endl;
#endif
}
MsgPacket::MsgPacket(int source, int destination):
PacketAddress(source,destination)
{
}
MsgPacket::MsgPacket(int source, int destination, int port):
PacketAddress(source,destination)
{
_port = port;
}
MsgPacket::MsgPacket(int source, int destination, int type, int port, std::string data):
PacketAddress(source, destination)
{
_source = source;
_dest = destination;
_type = type;
_data = data;
_port = port;
}
string MsgPacket::dataOutput()
{
stringstream output;//create a stringstream
output << setw(4) << setfill('0') << _source << ":" << setw(4) << setfill('0') << _dest << ":" << setw(4) << setfill('0') << _type << ":" << setw(4) << setfill('0') << _port << ":" << _data;
return output.str();
}
string MsgPacket::toString()
{
stringstream output;//create a stringstream
output << "[" << showbase << hex << this << "] S:[" << _source << "] D:[" << _dest << "] P:[" << _type << "] T:[" << _port << "]" << " DATA[" << _data << "]";
return output.str();
}
Undefined reference to means that you're trying to refer to something that cannot be linked. Are you linking your two cpp files together?