How to pass functions defined in a class as arguments to functions? - c++

getMessage method extracts the first letter in each word of input string.
Example:
input = "Find the first letters of this Sentence"
output = FtflotS
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;
class HiddenMessage {
public:
bool space (char c) {
return isspace(c);
}
bool not_space (char c) {
return !isspace (c);
}
string getMessage(string text) {
string ret;
typedef string::const_iterator iter;
iter i, j;
i = text.begin();
while (i != text.end()) {
i = find_if (i, text.end(), not_space); // error here
j = find_if (i, text.end(), space); // error here
if (i != text.end()) {
ret += *i;
}
i = j;
}
return ret;
}
};
//compiler error:
//error: invalid use of non-static member function
I tried making definitions of space and not_space static and it did
not work.
getMessage is called from the main below:
#include <ctime>
#include <cmath>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
if (argc == 1)
{
cout << "Testing HiddenMessage (250.0 points)" << endl << endl;
for (int i = 0; i < 20; i++)
{
ostringstream s; s << argv[0] << " " << i;
int exitCode = system(s.str().c_str());
if (exitCode)
cout << "#" << i << ": Runtime Error" << endl;
}
int T = time(NULL)-1456061889;
double PT = T/60.0, TT = 75.0;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
cout << endl;
cout << "Time : " << T/60 << " minutes " << T%60 << " secs" << endl;
cout << "Score : " << 250.0*(.3+(.7*TT*TT)/(10.0*PT*PT+TT*TT)) << " points" << endl;
}
else
{
int _tc; istringstream(argv[1]) >> _tc;
HiddenMessage _obj;
string _expected, _received;
time_t _start = clock();
switch (_tc)
{
case 0:
{
string text = "compete online design event rating";
_expected = "coder";
_received = _obj.getMessage(text); break;
}
case 1:
{
string text = " c o d e r ";
_expected = "coder";
_received = _obj.getMessage(text); break;
}
case 2:
{
string text = "round elimination during onsite contest";
_expected = "redoc";
_received = _obj.getMessage(text); break;
}
case 3:
{
string text = " ";
_expected = "";
_received = _obj.getMessage(text); break;
}
/*case 4:
{
string text = ;
_expected = ;
_received = _obj.getMessage(text); break;
}*/
/*case 5:
{
string text = ;
_expected = ;
_received = _obj.getMessage(text); break;
}*/
/*case 6:
{
string text = ;
_expected = ;
_received = _obj.getMessage(text); break;
}*/
default: return 0;
}
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
double _elapsed = (double)(clock()-_start)/CLOCKS_PER_SEC;
if (_received == _expected)
cout << "#" << _tc << ": Passed (" << _elapsed << " secs)" << endl;
else
{
cout << "#" << _tc << ": Failed (" << _elapsed << " secs)" << endl;
cout << " Expected: " << "\"" << _expected << "\"" << endl;
cout << " Received: " << "\"" << _received << "\"" << endl;
}
}
}

You have two problems.
The first, is you are supplying non-static class member functions (space and not_space) to find_if which expects a function object or pointer. So, declare them static if you want them to remain your class, or make them global by placing them outside the class.
The second, your string text parameter is non-const, but, you are working with a const interator type. begin() and end() calls will return const or non-const iterator depending on the calling object (text in this case) and whether or not it is const qualified. So, declare your text parameter as const.

Related

c++ netplan ubuntu yaml read and create

i have create a c++ app and need to read Ubuntu Netplan yaml files.
I found many websites with a lot of helpful information. mostly everything just does not work with netplan files. it crashes every time, usually when I set the root node to network. However, it is necessary because you still do not know what network card it is.
network.yaml
network:
ethernets:
eth0:
addresses:
- 192.168.0.30/24
dhcp4: false
gateway4: "192.168.0.1"
nameservers:
addresses:
- "211.211.190.30"
- "211.160.60.1"
- "8.8.8.8"
search:
- Network.local
renderer: networkd
version: 2
it must save into a struct for another works.
Parsing yaml with yaml cpp
yaml-cpp Easiest way to iterate through a map with undefined values
yaml-cpp read sequence in item
http://albertocorona.com/yaml-cpp-a-small-tutorial-to-serialization/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <dirent.h>
#include <yaml-cpp/yaml.h>
#include <yaml-cpp/node/node.h>
#include <yaml-cpp/node/iterator.h>
using namespace std;
static string path02 = "/Netzwerk.yaml";
struct NetInfo {
int ID;
string version;
string renderer;
string IF_Type;
string name;
string dhcp4;
vector<string> addresseIF;
string gateway4;
vector<string> NSsearch;
vector<string> NSaddress;
};
int main(){
NetInfo yamlsafe;
YAML::Node config = YAML::LoadFile(path02);
string NetzwerkTyp = config["network"]["ethernets"].as<std::string>();
string NetzManager = config["network"]["renderer"].as<string>();
string If_Name = config["network"]["eth0"].as<string>();
string DHCP4 = config["eth0"]["addresses"].as<string>();
string IP = config["eth0"]["dhcp4"].as<string>();
string Gateway = config["eth0"]["gateway4"].as<string>();
string NS_IP = config["nameservers"]["addresses"].as<string>();
string NS_Search = config["nameservers"]["search"].as<string>();
cout <<"NetzwerkTyp:" << "\t" << NetzwerkTyp << endl;
cout <<"Netz Manager:" << "\t" << NetzManager << endl;
cout <<"If-Name:" << "\t" << If_Name << endl;
cout <<"DHCP4" << "\t" << DHCP4 << endl;
cout <<"IP" << "\t" << IP << endl;
cout <<"Gateway" << "\t" << Gateway << endl;
cout <<"NS-IP" << "\t" << NS_IP << endl;
cout <<"NS-Search" << "\t" << NS_Search << endl;
//second test
YAML::Node config1 = YAML::LoadFile(path02);
const YAML::Node& sensors = config1["network"];
for (YAML::const_iterator it = sensors.begin(); it != sensors.end(); ++it) {
const YAML::Node& sensor = *it;
std::cout << "address: " << sensor["addresses"].as<std::string>() << "\n";
std::cout << "dhcp: " << sensor["dhcp4"].as<std::string>() << "\n";
}
return 0;
}
yes i had the same think i've bin see this tipe but
nothing is what it makes. it hange up the QT ide.
my second thing is the second test below.
YAML::Node config1 = YAML::LoadFile(path02);
const YAML::Node& node1 = config1["network"];
//network: ------------------------>node2
const YAML::Node& node2 = node1["network"]["ethernets"];
// ethernets: ------------------>node3
const YAML::Node& node3 = node2["ethernets"]["eth0"];
// eth0: --------------------->node4
const YAML::Node& node4 = node3["eth0"]["addresses"];
// addresses: ----------------------N1-> - seq1
const vector& node4s1 = node4["addresses"];
// - 192.168.0.30/24-----------------> - seq1 -p1
const YAML::Node& node4 = node3["eth0"]["dhcp4"];
// dhcp4: false ------------------>node4-2
const YAML::Node& node4 = node3["eth0"]["gateway4"];
// gateway4: "192.168.0.1"-------->node4-3
const YAML::Node& node4 = node3["eth0"]["nameservers"];
// nameservers: ------------------>node4-4
const vector& node4s2 = node4["nameservers"]["addresses"];
// addresses: --------------------N5-> - seq2
// - "211.211.190.30"--------------> - seq2 - p1
// - "211.160.60.1"----------------> - seq2 - p2
// - "8.8.8.8"---------------------> - seq2 - p3
const vector& node4s3 = node4["nameservers"]["search"];
// search: -----------------------N6-> - seq3
// - Network.local-----------------> - seq3 - p1
const YAML::Node& node2 = node1["network"]["renderer"];
// renderer: networkd---------->node5
const YAML::Node& node2 = node1["network"]["version"];
// version: 2------------------>node6
this is what i thing about it but it is not working.
Ok this is the answer i have a struct and i can read all nodes.
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <dirent.h>
#include <yaml-cpp/yaml.h>
#include <yaml-cpp/node/iterator.h>
using namespace std;
struct DateiLesen {
string version;
string renderer;
string IF_Type;
string name;
string dhcp4;
string dhcp6;
vector<string> addresseIF;
string gateway4;
string gateway6;
vector<string> NSsearch;
vector<string> NSaddress;
};
static vector<DateiLesen> DLS2;
static string path = "/QTProjects/YAML-15/test/Netzwerk.yaml";
void Yaml_lesen(){
YAML::Node nodew = YAML::LoadFile(path);
string NetIf = "eth0";
DLS2.push_back(DateiLesen());
if (nodew["network"]) {
if (nodew["network"]["version"]) {
DLS2[0].version = nodew["network"]["version"].as<string>();
//std::cout << nodew["network"]["version"].as<std::string>() << "\n";
}
if (nodew["network"]["renderer"]) {
DLS2[0].renderer = nodew["network"]["renderer"].as<std::string>();
//std::cout << nodew["network"]["renderer"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"]) {
DLS2[0].IF_Type = "ethernets";
if (nodew["network"]["ethernets"][NetIf]) {
if (nodew["network"]["ethernets"][NetIf]["dhcp4"]) {
DLS2[0].dhcp4 = nodew["network"]["ethernets"][NetIf]["dhcp4"].as<string>();
//std::cout << nodew["network"]["ethernets"][NetIf]["dhcp4"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"][NetIf]["dhcp6"]) {
DLS2[0].dhcp6 = nodew["network"]["ethernets"][NetIf]["dhcp6"].as<string>();
//std::cout << nodew["network"]["ethernets"][NetIf]["dhcp6"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"][NetIf]["addresses"]) {
if (nodew["network"]["ethernets"][NetIf]["addresses"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["ethernets"][NetIf]["addresses"].size(); ++it) {
DLS2[0].addresseIF.push_back(nodew["network"]["ethernets"][NetIf]["addresses"][it].as<std::string>());
//cout << nodew["network"]["ethernets"][NetIf]["addresses"][it].as<std::string>() << "\n";
}
}
}
if (nodew["network"]["ethernets"][NetIf]["gateway4"]) {
DLS2[0].gateway4 = nodew["network"]["ethernets"][NetIf]["gateway4"].as<string>();
//std::cout << nodew["network"]["ethernets"][NetIf]["gateway4"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"][NetIf]["gateway6"]) {
DLS2[0].gateway6 = nodew["network"]["ethernets"][NetIf]["gateway6"].as<string>();
//std::cout << nodew["network"]["ethernets"][NetIf]["gateway4"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"][NetIf]["nameservers"]) {
//cout << "Nameservers" << endl;
if (nodew["network"]["ethernets"][NetIf]["nameservers"]["search"]) {
if (nodew["network"]["ethernets"][NetIf]["nameservers"]["search"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["ethernets"][NetIf]["nameservers"]["search"].size(); ++it) {
DLS2[0].NSsearch.push_back(nodew["network"]["ethernets"][NetIf]["nameservers"]["search"][it].as<std::string>());
//cout << nodew["network"]["ethernets"][NetIf]["nameservers"]["search"][it].as<std::string>() << "\n";
}
}
}
if (nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"]) {
if (nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"].size(); ++it) {
DLS2[0].NSaddress.push_back(nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"][it].as<std::string>());
//cout << nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"][it].as<std::string>() << "\n";
}
}
}
}
}
}else if(nodew["network"]["wifis"]){
DLS2[0].IF_Type = "wifis";
if (nodew["network"]["wifis"][NetIf]) {
if (nodew["network"]["wifis"][NetIf]["dhcp4"]) {
DLS2[0].dhcp4 = nodew["network"]["wifis"][NetIf]["dhcp4"].as<string>();
//std::cout << nodew["network"]["wifis"][NetIf]["dhcp4"].as<std::string>() << "\n";
}
if (nodew["network"]["wifis"][NetIf]["dhcp6"]) {
DLS2[0].dhcp6 = nodew["network"]["wifis"][NetIf]["dhcp6"].as<string>();
//std::cout << nodew["network"]["wifis"][NetIf]["dhcp6"].as<std::string>() << "\n";
}
if (nodew["network"]["wifis"][NetIf]["addresses"]) {
if (nodew["network"]["wifis"][NetIf]["addresses"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["wifis"][NetIf]["addresses"].size(); ++it) {
DLS2[0].addresseIF.push_back(nodew["network"]["wifis"][NetIf]["addresses"][it].as<std::string>());
//cout << nodew["network"]["wifis"][NetIf]["addresses"][it].as<std::string>() << "\n";
}
}
}
if (nodew["network"]["wifis"][NetIf]["gateway4"]) {
DLS2[0].gateway4 = nodew["network"]["wifis"][NetIf]["gateway4"].as<string>();
//std::cout << nodew["network"]["wifis"][NetIf]["gateway4"].as<std::string>() << "\n";
}
if (nodew["network"]["wifis"][NetIf]["gateway6"]) {
DLS2[0].gateway6 = nodew["network"]["wifis"][NetIf]["gateway6"].as<string>();
//std::cout << nodew["network"]["wifis"][NetIf]["gateway4"].as<std::string>() << "\n";
}
if (nodew["network"]["wifis"][NetIf]["nameservers"]) {
cout << "Nameservers" << endl;
if (nodew["network"]["wifis"][NetIf]["nameservers"]["search"]) {
if (nodew["network"]["wifis"][NetIf]["nameservers"]["search"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["wifis"][NetIf]["nameservers"]["search"].size(); ++it) {
DLS2[0].NSsearch.push_back(nodew["network"]["wifis"][NetIf]["nameservers"]["search"][it].as<std::string>());
//cout << nodew["network"]["wifis"][NetIf]["nameservers"]["search"][it].as<std::string>() << "\n";
}
}
}
if (nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"]) {
if (nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"].size(); ++it) {
DLS2[0].NSaddress.push_back(nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"][it].as<std::string>());
//cout << nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"][it].as<std::string>() << "\n";
}
}
}
}
}
}else if(nodew["network"]["bonds"]){
}else if(nodew["network"]["bridges"]){
}else if(nodew["network"]["vlans"]){
}
}
}
int main(){
Yaml_lesen();
for (unsigned long S = 0; S < DLS2.size(); S++){
cout << DLS2[S].renderer << endl;
cout << DLS2[S].name << endl;
cout << DLS2[S].IF_Type << endl;
cout << DLS2[S].dhcp4 << endl;
for (unsigned long S2 = 0; S2 < DLS2[S].addresseIF.size(); S2++){
cout << DLS2[S].addresseIF[S2] << endl;
}
cout << DLS2[S].gateway4 << endl;
for (unsigned long S2 = 0; S2 < DLS2[S].addresseIF.size(); S2++){
cout << DLS2[S].NSsearch[S2] << endl;
}
for (unsigned long S2 = 0; S2 < DLS2[S].addresseIF.size(); S2++){
cout << DLS2[S].NSaddress[S2] << endl;
}
}
return 0;
}

can't write on a string in C++

I have the next function and i want to print some parameters separated by a comma, my problem is that the console didn't show anything when "parametro[i] = linea[i]" in the FOR iteration.
Example:
Parametro 1: []
void funcionSeparadora (string linea){
int numParametros = 1;
string parametro;
for (int unsigned i=0;i<linea.length();i++){
if (linea[i] == ','){
cout <<"Parámetro "<<numParametros<<": "<<"["<< parametro <<"]"<< '\n';
numParametros++;
}
else (parametro[i] = linea[i]);
}
}
Mostly the way you handle the filling of parametro was wrong. Fixed version:
void funcionSeparadora(string linea) {
int numParametros = 1;
string parametro;
for (int unsigned i = 0; i<linea.length(); i++) {
if (linea[i] == ',') {
cout << "Parámetro " << numParametros << ": " << "[" << parametro << "]" << '\n';
numParametros++;
parametro.clear();
}
else {
parametro += linea[i];
}
}
if (!parametro.empty()) {
cout << "Parámetro " << numParametros << ": " << "[" << parametro << "]" << '\n';
}
}
Points you missed
Use curly brackets in else condition
Use size_t instead of unsigned in in for loop
initialize the parametro variable with necessary length
Try this
#include <iostream>
#include <string>
using namespace std;
void funcionSeparadora(string linea) {
int numParametros = 1;
string parametro(linea.length(),' ');
for (size_t i = 0; i < linea.length(); i++) {
if (linea[i] == ',') {
cout << "Parámetro " << numParametros << ": " << "[" << parametro << "]" << endl;
numParametros++;
}
else {
parametro[i] = linea[i];
}
}
}
int main()
{
funcionSeparadora("what is this,");
system("pause");
return 0;
}

c++ Sharing list between main an exterior function

I am making a rabbit population simulator for a challenge I am doing. I have a map of class objects. I also have a list which contains the keys for the map. Each round of the simulator I want to add more objects to the class, and update my map and list. To do this I wrote a separate "creation" function which will randomly generate new class objects and add them to a map and add the keys to a list.
The problem is when I call the creation function, then iterate through the map using the list it shows the map or list is empty (not sure which). If I iterate through the map before leaving the function it only shows the newest objects. If I move the code for the function into the main function, it works correctly (calling it twice gives me the new objects created in the first iteration of the code, and also the objects created by the second iteration).
I am guessing that a new list or map is being created each time the function is called and is overwriting the old list or map. How can I get the list and map to pass between the main function and the creation function?
Here is my code:
#include "stdafx.h"
#include <iostream>
#include "windows.h"
#include <string>
#include <sstream>
#include <array>
#include <time.h>
#include <conio.h>
#include <map>
#include <list>
class Bunny
{
public:
char fname;
int sex, age, color, status;
Bunny(int, int, int, int);
Bunny();
int s() { return (sex); }
int a() { return (age); }
int c() { return(color);}
int st() { return (status);}
int aging(int age) { return (age + 1); }
};
Bunny::Bunny(int s, int a, int c, int st)
{
sex = s;
age = a;
color = c;
status = st;
}
Bunny::Bunny(){}
void creation(std::map<std::string, Bunny> bunnies, std::list<std::string>names, int births);
std::string firstname(int s, int num)
{
std::string name;
if (s == 0)
{
switch (num)
{
case (0) :
name = "Tim";
break;
case (1) :
name = "Tom";
break;
case (2) :
name = "Mark";
break;
case (3) :
name = "Bob";
break;
case (4) :
name = "Rob";
break;
}
}
if (s == 1)
{
switch (num)
{
case (0) :
name = "Suzy";
break;
case (1) :
name = "Linda";
break;
case (2) :
name = "Mary";
break;
case (3) :
name = "Jan";
break;
case (4) :
name = "Julie";
break;
}
}
return (name);
}
void main()
{
int num = rand() % 5;
int n, births = 10;
std::list<std::string>names;
std::map<std::string, Bunny> bunnies;
srand(time(0));
creation(bunnies, names, births);
std::cout << "Number" << "\t" << "Name" << "\t" << "age" << "\t" << "Sex" << "\t" << "Color" << "\t" << "Vampire?" "\n";
n = 0;
for (std::list<std::string>::iterator it = names.begin(); it != names.end(); it++)
{
n++;
std::cout << n << "\t";
std::cout << " " << *it;
std::cout << "\t" << bunnies[*it].a() << "\t" << bunnies[*it].s() << "\t" << bunnies[*it].c() << "\t" << bunnies[*it].st() << "\n";
}
creation(bunnies, names, births);
_getch();
}
/*void year()
{
for (std::list<std::string>::iterator it = names.begin(); it != names.end(); it++)
{
bunnies[*it].aging(bunnies[*it].a())
}
}*/
void creation(std::map<std::string, Bunny> bunnies,std::list<std::string> names,int births)
{
int n;
for (n = 0; n < births; n++)
{
int num = std::rand() % 5;
char id = (std::rand() % 100) + 20;
int s = std::rand() % 2;
std::string f = firstname(s, num) + '_' + id;
int a = 0;
int c = std::rand() % 5;
int st;
if (rand() % 50 == 43) st = 1; else st = 0;
bunnies[f] = Bunny(s, a, c, st);
names.push_front(f);
//std::cout << f << " " << bunnies[f].a() << " " << bunnies[f].c() << "\n";
}
std::cout << "Number" << "\t" << "Name" << "\t" << "age" << "\t" << "Sex" << "\t" << "Color" << "\t" << "Vampire?" "\n";
n = 0;
for (std::list<std::string>::iterator it = names.begin(); it != names.end(); it++)
{
n++;
std::cout << n << "\t";
std::cout << *it;
std::cout << "\t" << bunnies[*it].a() << "\t" << bunnies[*it].s() << "\t" << bunnies[*it].c() << "\t" << bunnies[*it].st() << "\n";
}
}
Your problem is that your main function is passing your map and list by value instead of passing by reference. This means that your creation function is receiving a copy of the existing map/list, rather than a reference to the original one you created. Since it is then only making edits to that copy, any changes it makes will not be reflected in the main function.
Change your creation function from:
void creation(std::map<std::string, Bunny> bunnies, std::list<std::string>names, int births)
to
void creation(std::map<std::string, Bunny>& bunnies, std::list<std::string>& names, int births)

The code is printing the same values when it should be randomly generating each ovr and also it is not printing the first value in the array

The issue that I am having is that with the code below, each plOvr for all of the class objects is the same. This causes them to have the same stats for everything. Also, I have an array with names that should be printed but it is skipping the first value.
using namespace std;
class Player
{
public:
int plOvr;
float plSpg, plSps;
string werk;
void setPlayeName(string);
string plName;
void setPlyrVal()
{
srand (time(NULL));
plOvr = rand()% 29 + 70;
plSps = plOvr / 10;
plSpg = plSps / 2;
}
};
void Player::setPlayeName(string werk)
{
plName = werk;
}
int main()
{
Player plyr1,plyr2,plyr3,plyr4,plyr5;
string firstTime;
string name[5] = {"Eric Gelinas","John Merill", "Jaromir Jagr", "Travis Zajac","Reid Boucher"};
bool firstOp;
cout << "Is this the first time this program has run?" << endl;
cin >> firstTime;
if (firstTime == "Yes" || firstTime == "yes")
{
firstOp == firstOp;
plyr1.setPlyrVal();
plyr1.setPlayeName(name[1]);
plyr2.setPlyrVal();
plyr2.setPlayeName(name[2]);
plyr3.setPlyrVal();
plyr3.setPlayeName(name[3]);
plyr4.setPlyrVal();
plyr4.setPlayeName(name[4]);
plyr5.setPlyrVal();
plyr5.setPlayeName(name[5]);
ofstream playerSaveData;
playerSaveData.open ("savedata.txt");
playerSaveData << plyr1.plName << "," << plyr1.plOvr << "," << plyr1.plSpg << "," << plyr1.plSps << "\n";
playerSaveData << plyr2.plName << "," << plyr2.plOvr << "," << plyr2.plSpg << "," << plyr2.plSps << "\n";
playerSaveData << plyr3.plName << "," << plyr3.plOvr << "," << plyr3.plSpg << "," << plyr3.plSps << "\n";
playerSaveData << plyr4.plName << "," << plyr4.plOvr << "," << plyr4.plSpg << "," << plyr4.plSps << "\n";
playerSaveData << plyr5.plName << "," << plyr5.plOvr << "," << plyr5.plSpg << "," << plyr5.plSps << "\n";
playerSaveData.close();
cout << "done.\n";
}
else
{
firstOp == !firstOp;
}
return 0;
}
You may use std::uniform_int_distribution<int> and an engine as std::mt19937 from <random>.
The engine (as srand) has to be initialized with seed only once.
Your program rewritten:
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
#include <random>
class Player
{
public:
void setPlayeName(const std::string& name) { plName = name; }
void setPlyrVal(std::mt19937& rand_engine)
{
std::uniform_int_distribution<int> distr(70, 98);
plOvr = distr(rand_engine);
plSps = plOvr / 10;
plSpg = plSps / 2;
}
public:
int plOvr;
float plSpg, plSps;
std::string werk;
std::string plName;
};
int main()
{
std::mt19937 rand_engine(time(nullptr));
Player plyrs[5];
const std::string names[5] = {"Eric Gelinas","John Merill", "Jaromir Jagr", "Travis Zajac","Reid Boucher"};
std::cout << "Is this the first time this program has run?" << std::endl;
std::string firstTime;
std::cin >> firstTime;
if (firstTime == "Yes" || firstTime == "yes") {
for (int i = 0; i != 5; ++i) {
plyrs[i].setPlyrVal(rand_engine);
plyrs[i].setPlayeName(names[i]);
}
std::ofstream playerSaveData;
playerSaveData.open ("savedata.txt");
for (const auto& plyr : plyrs) {
playerSaveData << plyr.plName << "," << plyr.plOvr << "," << plyr.plSpg << "," << plyr.plSps << "\n";
}
std::cout << "done." << std::endl;
}
return 0;
}
Live example
You should call srand() only once in the whole program, instead of calling it before each rand().

C++ char vector addition

This is a part of a program that I am writing to compute the addition of two integers as strings. (Writing my own bigInt class).
There appears to be a problem when I am adding the two integers together. Because they are both in vectors of char type, I had to add a '0' to each element of the vector before concatenating it into a string.
However, the results are still not what I am expecting:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string const Number = "1000";
string const Number2 = "1000";
vector<char> reverse;
vector<char> reverse2;
//cout << (rostrNumber[1] - '0') << endl;
cout << "Original Number: " << Number << endl;
reverse.clear();
for (int i = Number.size() - 1; i >= 0; i--)
{
reverse.push_back(Number[i]);
}
cout << "Reversed: " << endl;
cout << reverse[0] << reverse[1] << reverse[2] << reverse[3] << endl;
cout << endl << endl;
reverse2.clear();
{
for (int i = Number2.size() - 1; i >= 0; i--)
{
reverse2.push_back(Number[i]);
}
}
cout << "Adding these two integers" << endl;
vector<char> const rcvN1 = reverse;
vector<char> const rcvN2 = reverse2;
vector<char> Results;
Results.clear();
//Local copies
vector<char> vN1 = rcvN1;
vector<char> vN2 = rcvN2;
int iSize1 = vN1.size();
int iSize2 = vN2.size();
int i, iSize = iSize2;
int iC = 0, iR;
for (i = 0; i<iSize; i++)
{
iR = vN1[i] + vN2[i] + iC;
if (iR > 9)
{
iR -= 10;
iC = 1;
}
else
iC = 0;
Results.push_back(iR);
cout << Results[0] << endl;
}
if (iC > 0)
Results.push_back(iC);
string ostr;
vector<char>::const_reverse_iterator rIter = Results.rbegin();
for (; rIter != Results.rend(); rIter++)
ostr += *rIter +'0';
cout << "Results: " << ostr << endl;
system("PAUSE");
return 0;
}