I'm a true beginner and this is really complicated for me. I've been looking for an answer but i have not been able to find it here or if i have seen it.. it seems to be complicated for me.
Here is what I'm trying to do:
I have this headers
#include <iostream>
#include <string>
#include <vector>
And i have this structs
struct stFecha {
int dia;
int mes;
int ano;
};
struct stPersona {
string cedula;
string nombre;
string apellido;
stFecha fechaNacimiento;
char estado;
};
struct stCuentaBancaria{
string numeroCuenta;
string nombreOficialBancario;
double totalDebito;
double totalCredito;
vector<stPersona> clientesCuenta;
char estado;
i declared these vectors that are the ones i will be working with
vector<stPersona> clientes;
vector<stCuentaBancaria> cuentas;
And this is the code i'm using to iterate through the structs and check if a person already exists in the record.
for( vector<stPersona>::iterator it = clientes.begin(); !existe && it != clientes.end(); ++it )
{
existe = cedula.compare( (*it).cedula ) == 0 ;
if ( existe )
{
cout << "NOMBRE :" << (*it).nombre << '\n'
<< "APELLIDO :" << (*it).apellido << '\n'
<< "CEDULA :" << (*it).cedula << '\n'
<< "FECHA DE NACIMIENTO DD/MM/AAAA:\n"
<< "DIA: " << (*it).fechaNacimiento.dia << '\n'
<< "MES: " << (*it).fechaNacimiento.mes << '\n'
<< "A\xA5O: " << (*it).fechaNacimiento.ano << '\n'
<< "ESTADO: "<< (*it).estado << '\n';
}
I can see that even though fechaNacimientois a struct i can accesso the data in this struct easily because it is not a vector.
In the other hand before i add a new account to the vector cuentas i need to check if the ID or cedula is registered into my customer's clientes data. so I'm using this following code to find if the record exists.
stCuentaBancaria cuenta;
cout << "CEDULA DEL CLIENTE: ";
cin >> cedula;
bool existe = false;
for ( vector<stPersona>::iterator it = clientes.begin(); !existe && it != clientes.end(); ++it )
{
existe = cedula.compare( (*it).cedula ) == 0;
if ( existe )
{
cuenta.clientesCuenta.push_back((*it));
}
From my perspective it is supposed to copy the record found in clientes which is type stPersonato clientesCuenta which is as well a struct stPersona within the struct stCuentas which stands for the banking accounts. so far i get no errors.
But here is where i dont see how to get things working for me...
I wish to consult the records and when it finds the desired record to display the data within the record but when i did, as before with the iterator of the customers clientes, this one doesnt work. It contains a vector inside it gives me an error
cout<<"\n\n2.CONSULTA POR CUENTA\n";
string cuenta;
cout << "INTRODUCIR CUENTA A CONSULTAR .:";
cin >> cuenta;
bool existe = false;
for( vector<stCuentaBancaria>::iterator it = cuentas.begin(); !existe && it != cuentas.end(); ++it )
{
existe = cuenta.compare( (*it).numeroCuenta ) == 0 ;
if ( existe )
{
cout << "NUMERO DE CUENTA :" << (*it).numeroCuenta << '\n'
<< "NOMBRE OFICIAL DE CUENTA :" << (*it).nombreOficialBancario << '\n'
<< "TOTAL DEBITO : " << (*it).totalDebito << '\n'
<< "TOTAL CREDITO: " << (*it).totalCredito << '\n'
<< "ESTADO: "<< (*it).estado << '\n'
<< "TUTORIALES DE CUENTA: " << (*it).clientesCuenta << '\n';
}
I tried using (*it).clientesCuentabut this is the vector struct stPersonaswithin the vector cuentas previously declarated.
I dont know how do i get access to display this data nor how to get access to modify it in the future if i find it.
Please help.
additional note: I'm accessing this data through functions
int manejoCuentas(vector<stCuentaBancaria> &cuentas,vector<stPersona> &clientes, int &opcionMenu)
And this is how i send the data from the main function
manejoCuentas(cuentas, clientes, opcion);
My english is not very good thanks for reading this and any help would be more than welcome
Defining following three overloading of the operator <<, we can simplify the code that outputs the members of your PODs.
Since stFecha, stPersona and stCuentaBancaria are all POD types and their members are all public, we do not need to define friend functions on them:
#include <ostream>
std::ostream& operator<<(std::ostream& o, const stFecha& fecha)
{
o << "DIA : " << fecha.dia << '\n';
o << "MES : " << fecha.mes << '\n';
o << "A\\xA5O: " << fecha.ano;
return o;
}
std::ostream& operator<<(std::ostream& o, const stPersona& persona)
{
o << "NOMBRE : " << persona.nombre << '\n';
o << "APELLIDO : " << persona.apellido << '\n';
o << "CEDULA : " << persona.cedula << '\n';
o << "FECHA DE NACIMIENTO DD/MM/AAAA:\n";
o << persona.fechaNacimiento << '\n';
o << "ESTADO : " << persona.estado;
return o;
}
std::ostream& operator<<(std::ostream& o, const stCuentaBancaria& bancaria)
{
o << "NUMERO DE CUENTA : " << bancaria.numeroCuenta << '\n';
o << "NOMBRE OFICIAL DE CUENTA : " << bancaria.nombreOficialBancario << '\n';
o << "TOTAL DEBITO : " <<bancaria.totalDebito << '\n';
o << "TOTAL CREDITO : " << bancaria.totalCredito << "\n\n";
o << "TUTORIALES DE CUENTA\n";
for(const auto& ceunta_i : bancaria.clientesCuenta){
o << ceunta_i << "\n\n";
}
o << "ESTADO: "<< bancaria.estado;
return o;
}
Then you can output the data of each element of std::vector<stCuentaBancaria> cuentas to std::cout or some other output stream with just a one liner as follows.
DEMO
std::cout << *it << std::endl;
Override the function to output a vector of stCuentaBancaria
ostream& operator<<(ostream& os, const vector &cuentas)
for(int i=0; i< cuentas.size(); i++){
os << "TUTORIALES DE CUENTA: " << i << ' ' << cuentas[i] << '\n';
}
return *os;
}
Related
I was wondering how can I print 2 for loops next to each other?
These are loops:
for(vector<Student>::iterator it = studenti.begin(); it != studenti.end(); ++it)
cout << "| " << it->brojIndeksa << " " << it->ime << " " << it->prezime;
for(map<string,string>::iterator it = ocjene.begin(); it!= ocjene.end(); ++it)
cout << " " << it->first << " - " << it->second << endl;
the output I want:
| brojIndeksa ime prezime first - second
| brojIndeksa ime prezime first - second
| brojIndeksa ime prezime first - second
the output I have:
| brojIndeksa ime prezime| brojIndeksa ime prezime first - second
first - second
EDIT:
struct Predmet {
string naziv;
string odsjek;
istream& dodaj_predmet(istream &);
void sort_predmeti();
};
struct Student {
string brojIndeksa;
string ime;
string prezime;
map<std::string, string> ocjene;
istream& dodaj_studenta(istream &);
void sort_studenti();
};
map<std::string, string> ocjene contains 2 strings for input, 1st one needs to be naziv from Predmet structure.
NEW OUTPUT:
| 1808 John Doe EJ 10
| PIM 10
| 1809 Jessica Doe PIM 10
You could iterate using both iterators in the same loop:
auto studenti_it = studenti.begin();
auto ocjene_it = ocjene.begin();
for (; studenti_it != studenti.end() && ocjene_it != ocjene.end(); ++studenti_it, ++ocjene_it)
{
// Print using both iterators...
}
After your edit where we see that the map is a member of the Student structure, I'm guessing what you want is to iterate over first the studenti vector, and then inside it have a loop for the Student::ocjene map?
Then you would have something like
// First iterate over the vector
for (auto const& student : studenti)
{
std::cout << "| " << student.brojIndeksa << " " << student.ime << " " << student.prezime << '\n';
// Then inside iterate over the map
for (auto const& oj : student.ocjene)
{
std::cout << '\t' << oj.first << ' ' << oj.second << '\n';
}
}
I am relatively new to C++. I am hoping to get assistance creating an overload operator that will permit me to use a literal string with a class I am writing. This project is for learning.
I created a custom Date class (and have not worried about the actual logic in the class; I'm just trying to get the interface working and to understand where my roadblock is.
It may not look like it, but I have put in a lot of time on this, so an explanation designed for a beginning c++ progammer would be very helpful to me and anyone who follows in my footsteps.
Basically, I'd like to be able to do this with my class:
Date dt(5,6,92);//create class object
int myint;
myint = dt;//this works
string mystr;
mystr = dt("mm/dd/yy");//this does not compile
Thanks in advance. (A compilable test program shown below)
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
class Date
{
int mo, da, yr;
public:
Date(int m, int d, int y)
{
cout << "Constructor int m, int d, int y called " << endl;
mo = m; da = d; yr = y;
}
string getdatestr(const char *s = "") {//user sends in format "d2/" "mm/dd/yy" etc
cout << "getdatestr const char *s called mo = " << mo << " da = " << da << "yr = " << yr << endl;
return to_string(mo) + "/" + to_string(da) + "/" + to_string(yr);
}
int getdate(){
cout << "getdate int t called" << endl;
string tag;
tag = to_string(yr) + to_string(mo) + to_string(da);
return stoi(tag);
}
string getdate(string &str){
cout << "getdate with string as ref" << endl;
return "5/5/55";
}
int getdate(int &myint){
cout << "getdate with int as ref" << endl;
return 12345;
}
void setdate(string dt){
cout << "setdate string dt called " << dt << endl;
mo = 1;
da = 2;
yr = 2020;
}
void setdate(int intdte){
cout << "setdate int to " << intdte << endl;
mo = 99;//any int for now
da = 98;
yr = 1997;
}
void setdate(const char *dte){
cout << "setdate char* dte = " << dte << endl;
mo = 94;
da = 95;
yr = 1996;
}
~Date(){
cout << "destructor called" << endl;
}
//below code permits this in main(): myint = dt;
operator int() {
cout << "operator int()" << endl;
string tag;
tag = to_string(yr) + to_string(mo) + to_string(da);
return stoi(tag);
}
//end section to permit: myint = dt;
//what do I need so I can do this: mystr = dt("mm/dd/yy");, nothing below worked; I tried many more iterations
//than what are shown here
/*
operator string() {
cout << "operator string char" << endl;
return "hello world";
}
string operator = (string &rhs){
cout << "string" << endl;
return "return a string";
}
operator = (const string &rhs){
cout << "will this work?" << endl;
return *this;
}
char& operator = (char(&)[9]){
cout << "whoa, it worked" << endl;
//return "got it";
}
operator = (char*){
cout << "try again" << endl;
}
string operator const char(&)[9] {
cout << "one more time" << endl;
string *ptr;
ptr = "one more time";
return ptr;
}
//end nothing worked to permit me to do this mystr = dte("mm/dd/yy"); section
*/
};//end of class
int main()
{
//create a Date class object dt
Date dt(5, 6, 92);
dt.setdate("02/15/22");
cout << endl;
cout << "next two mystr messages return null because I " << endl;
cout << "can't seem to write a valid overload operator for a literal string" << endl;
string mystr;
//mystr = dt("mm/dd/yy");//does not compile (no match for call to '(Date) (const char [9])'
cout << "mystr using dt(str) = " << mystr << endl;
string myconv = "mm/dd/yy";
//mystr = dt(myconv);//does not compile (no match for call to '(Date) (std::__cxx11::string&)'
cout << "mystr using dt(mm//dd//yy) = " << mystr << endl;
cout << endl;
//this section works
//can I assign dt to an integer (as #days from a reference date)
cout << "this section seems to work" << endl;
int myint;
cout << "myint = dt;" << endl;
myint = dt;//does not compile
cout << "myint (using = dt;) = " << myint << endl;
cout << endl;
system("pause");
}
my program is reading in 2 text files, one is going into an array and one is priming read normally. The one that is being read into an array has an item code, price, quantity, and item name. When the item code matches with the code on the other text document I need to get the price associated with it and cant figure out how.
while (!purchasesFile.eof())
{
purchasesFile >> PurchaseItem >> purchaseQty;
cout << purchaseNum << " " << PurchaseItem << " " << setw(4) <<
purchaseQty << " # " << dollarSign << endl;
int n = 0;
if (inventoryRec[n].itemCode != PurchaseItem)
{
inventoryRec[n+1];
}
else
{
cout << inventoryRec[n].itemPrice << endl;
inventoryRec[n+1];
}
if (PurchaseItem == inventoryRec[itemCount].itemCode)
{
inventoryRec[itemCount].itemOnHand - purchaseQty;
purchaseAmount = inventoryRec[itemCount].itemPrice * purchaseQty;
cout << purchaseAmount << " " <<
inventoryRec[itemCount].itemOnHand;
purchaseCount++;
}
purchasesFile >> purchaseNum;
}
purchasesFile.close();
There are several statements in your code that do nothing:
inventoryRec[n+1];
inventoryRec[itemCount].itemOnHand - purchaseQty;
What you are looking for is probably something like the STL map
typedef struct inventory_item_t {
inventory_item_t(const std::string& item_code, double price, int quantity) :
item_code(item_code),
price(price),
quantity(quanity) { }
std::string item_code;
double price;
int quantity;
} inventory_item_t;
typedef std::map<std::string, inventory_item_t> inventory_items_t;
inventory_items_t inventory_items;
inventory_items.insert(make_pair("item1", inventory_item_t("item1", 1.0, 1)));
inventory_items.insert(make_pair("item2", inventory_item_t("item2", 1.1, 2)));
inventory_items.insert(make_pair("item3", inventory_item_t("item3", 1.2, 3)));
inventory_items_t::iterator inventory_item = inventory_items.find("item1");
if(inventory_item != inventory_items.end()) {
std::cout << "Inventory Item found - item_code: ["
<< inventory_item->first
<< "], price: ["
<< inventory_item->second.price
<< "]"
<< std::endl;
} else {
std::cout << "Inventory Item not found" << std::endl;
}
I hope this time my question is better formulated and formatted.
Here's the code that produces two separate outputs when I think it should not since I use everytime (I think) the overloaded operator<< for an enum type.
#include <iostream>
using namespace std;
enum Etat { Intact = 5 };
class Ship {
public:
Etat etat_;
Ship ( Etat t = Intact) : etat_(t) {}
~ Ship() {}
ostream& description ( ) const { return cout << "Etat: " << etat_ << " --- ";}
//---------------------------------------ˆˆˆˆ----
};
ostream& operator<< ( ostream& s, const Etat& etat_ )
{
switch ( etat_ )
{
case Intact: s << "intact"; break;
default: s << "unknown state";
}
return s;
}
ostream& operator<< ( ostream& s, Ship n ) { return s << "Etat: " << n.etat_ ; }
int main()
{
Etat etat_ = Intact;
cout << endl << endl << "Etat: "
<< etat_ << " \"cout << etat_\"" << endl << endl;
cout << Ship(etat_)
<< " \"cout << Ship(etat_)\"" << endl << endl;
cout << Ship(etat_).description()
<< " \"cout << Ship(etat_).description()\"" << endl << endl;
return 0;
}
This is what I get in the terminal:
Etat: intact "cout << etat_"
Etat: intact "cout << Ship(etat_)"
Etat: 5 --- 1 "cout << Ship(etat_).description()"
Can anyone explain to me why, in the last case, not only it takes the integer value of the enum attribut, but also adds a "1" after the test string " --- "???
The only thing I can think of is because I used an unorthodox return method in description(), ie 'return cout << ..", but it seems to work since the test string appears.
Is there a way to force the use of the operator<< overload in description()?
Thanks
In the description() function you are returning a reference to std::cout and use it in the std::cout call in main function. There is a reason why operator<< takes an ostream reference as it's first argument. You should modify your function like this and all should work:
ostream& description(ostream& os) const {
return os << "Etat: " << etat_ << " --- ";
}
The random "1" printed out there is caused likely due to the ostream in your example trying to print out reference to itself.
That's my first question here, so I would be glad to receive some support on the style I used to refer to my problem :). Here is the finished program, its main purpose is to split given words into halves and create words replacing the origin ones. Replaced words are build from its origins by spliting them into halves and taking even ones from the 1st half begining with the first letter of a word. Heres the complete code:
#include <iostream>
#include <string>
#include <cstdio>
#include <math.h>
using namespace std;
void obcinaczSlow(int);
int main(){
int ilosc;
cout << "Prosze o podanie ilosci prob: ";
cin>>ilosc;
cout << endl;
obcinaczSlow(ilosc);
cin.ignore();
cin.get();
return 0;
}
void obcinaczSlow(int ilosc_prob){
int i=0,j=0,dlugosc_slowa=0,dlugosc_polowy=0;
string *tablica_slow,budowane_slowo,aktualne_slowo,dodane;
tablica_slow = new string [ilosc_prob];
cout << "Prosze o podanie " << ilosc_prob << " slow" << endl;
cin.sync();
for(i=0;i<ilosc_prob;i++){
cout << "Prosze o podanie slowa numer: " << i+1 << endl;
cin>>aktualne_slowo;
tablica_slow[i] = aktualne_slowo;
}
for(i=0;i<ilosc_prob;i++){
aktualne_slowo = tablica_slow[i];
cout << "Aktualne slowo do przerobienia: " << aktualne_slowo << endl;
dlugosc_slowa = aktualne_slowo.length();
cout << "Dlugosc slowa do przerobienia: " << dlugosc_slowa << endl;
dlugosc_polowy = floor(dlugosc_slowa/2);
cout << "Dlugosc polowy slowa int: " << dlugosc_polowy << endl;
budowane_slowo.clear();
dodane.clear();
cout << "Budowane slowo to: " << budowane_slowo << endl;
for(j=0;j<=dlugosc_polowy;j=+2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}
tablica_slow[i] = budowane_slowo;
}
cout << "Slowa po transformacji wygladaja nastepujaco: " << endl;
for(i=0;i<ilosc_prob;i++){
cout << "Slowo o numerze " << i+1 << " : " << tablica_slow[i] << endl;
}
delete [] tablica_slow;
cin.sync();
}
The problem raises when program reaches the loop, that is supposed to append the letter pointed by the j-index using '.at' method from the string class. I can't find a solution even trying to debug it. Could You help me :)?
You have a typo here
for(j=0;j<=dlugosc_polowy;j=+2)
I assume you meant += instead of =+
for(j=0;j<=dlugosc_polowy;j+=2)
Otherwise you are just assigning 2 to j over and over again.
Your error is reversing two characters:
Change:
`j=+2` to `j+=2`
^^ ^^
(The way it is written j is assigned the value of 2, then, for the rest of its life, stays there.)
for(j=0;j<=dlugosc_polowy;j=+2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}
replace the j=+2 to j+=2
for(j=0;j<=dlugosc_polowy;j+=2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}