c++ netplan ubuntu yaml read and create - c++

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;
}

Related

How to sort files by descending the file size

I need to output the 5 largest files from the directory. For this, I use a boost filesystem c++. In the process of writing the program, I encountered difficulties. I can output all files from the directory, file size, file creation date and file attributes. In the vector I put the names of the files, but I just can not figure out how to sort by size. I need to output the 5 largest files from the specified directory. I think that you must first sort by file size by descending. That is, from a larger value to a smaller one. And then the scans are not needed. Most likely it needs to be done in a loop. Help me please.
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
void ShowAttributes(DWORD attributes);
void AttribFile(const char* str);
void Attrib();
int main(int argc, char* argv[])
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
if (argc < 2)
{
cout << "Using Name Directory" << endl;
return 1;
}
path Part(argv[1]);
try
{
if (exists(Part))
{
if (is_regular_file(Part))
{
cout << Part << " Size " << file_size(Part) << " bytes ";
time_t Time = last_write_time(Part);
cout << asctime(localtime(&Time)) << endl;
}
else if (is_directory(Part))
{
cout << "Directory " << Part << " include:" << endl;
vector<string> vecList;
for (auto j : directory_iterator(Part))
vecList.push_back(j.path().filename().string());
sort(vecList.begin(), vecList.end());
string filePath;
for (auto i : vecList)
{
cout << " " << i;
filePath = Part.parent_path().string() + "/" + i;
if (is_regular_file(filePath))
{
if (Is_Executable_File(filePath))
cout << "*";
cout << " Size " << file_size(filePath) << " bytes ";
time_t Time = last_write_time(Part);
cout << asctime(localtime(&Time)) << endl;
AttribFile(filePath.c_str());
}
cout << endl;
}
}
}
else
cout << Part << " Erroe!" << endl;
}
catch (const filesystem_error& ex)
{
cout << ex.what() << endl;
}
return 0;
}
void ShowAttributes(DWORD attributes)
{
if (attributes & FILE_ATTRIBUTE_ARCHIVE)
cout << " archive" << endl;
if (attributes & FILE_ATTRIBUTE_DIRECTORY)
cout << " directory" << endl;
if (attributes & FILE_ATTRIBUTE_HIDDEN)
cout << " hidden" << endl;
if (attributes & FILE_ATTRIBUTE_NORMAL)
cout << " normal" << endl;
if (attributes & FILE_ATTRIBUTE_READONLY)
cout << " read only" << endl;
if (attributes & FILE_ATTRIBUTE_SYSTEM)
cout << " system" << endl;
if (attributes & FILE_ATTRIBUTE_TEMPORARY)
cout << " temporary" << endl;
}
void AttribFile(const char* str)
{
DWORD attributes;
attributes = GetFileAttributesA(str);
ShowAttributes(attributes);
}
void Attrib()
{
char filename[MAX_PATH];
DWORD attributes;
cout << "Name of file: ";
cin >> filename;
attributes = GetFileAttributesA(filename);
ShowAttributes(attributes);
}
create a class or struct to hold the information you need on each file, e.g.
struct MyFile
{
std::string name;
size_t size;
}
create a vector of these and read all files from your folder
then sort the vector and give a custom comparison (e.g. in form of a lambda), see Sorting a vector of custom objects for details on that
Here's a program based on just the standard library that does what you seem to intend:
Live On Coliru
Update: Using C++11 and Boost Filesystem instead: Live On Coliru
#include <algorithm>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
namespace fs = std::filesystem;
struct tm *last_modified(fs::path const &p) {
auto ftime = fs::last_write_time(p);
auto cftime = decltype(ftime)::clock::to_time_t(ftime);
return std::localtime(&cftime);
}
bool is_executable(fs::path const& p) {
return fs::perms::none != (fs::status(p).permissions() &
(fs::perms::owner_exec |
fs::perms::group_exec |
fs::perms::others_exec));
}
void report(fs::path const& file) {
if (is_executable(file))
std::cout << "*";
std::cout << file << "\tSize:" << fs::file_size(file);
std::cout << "\tModified:" << std::asctime(last_modified(file));
}
template <typename Accessor, typename Cmp = std::less<> >
static auto compare_by(Accessor&& f, Cmp cmp = {}) {
return [f=std::forward<Accessor>(f),cmp](auto const& a, auto const& b) {
return cmp(f(a), f(b));
};
}
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << "Using: " << argv[0] << " [Name|Directory]" << std::endl;
return 1;
}
fs::path filespec(argv[1]);
try {
if (is_regular_file(filespec)) {
// print
report(filespec);
} else if (is_directory(filespec)) {
std::cout << "Directory " << filespec << " include:" << std::endl;
std::vector<fs::directory_entry> const entries { fs::directory_iterator{filespec}, {} };
// filter just files
std::vector<fs::path> files;
std::remove_copy_if(entries.begin(), entries.end(),
back_inserter(files),
[](auto& de) { return de.is_directory(); });
// get the top 5, or fewer
auto b = files.begin(),
top5 = b + std::min(5ul, files.size()),
e = files.end();
// ordered by size, descending
std::partial_sort(b, top5, e,
compare_by([](auto& p) { return fs::file_size(p); }, std::greater<>{}));
files.erase(top5, e);
// print
for (auto& f : files)
report(f);
} else {
std::cout << filespec << " Error!" << std::endl;
}
} catch (const fs::filesystem_error &ex) {
std::cout << ex.what() << std::endl;
}
}
Prints, e.g. for ./a.out /usr/lib:
Directory "/usr/lib/" include:
"/usr/lib/libruby-1.9.1-static.a" Size:3654748 Modified:Wed Nov 19 21:41:25 2014
"/usr/lib/libruby-1.9.1.so.1.9.1" Size:2087600 Modified:Wed Nov 19 21:41:20 2014
"/usr/lib/libruby-1.9.1.so" Size:2087600 Modified:Wed Nov 19 21:41:20 2014
"/usr/lib/libruby-1.9.1.so.1.9" Size:2087600 Modified:Wed Nov 19 21:41:20 2014
"/usr/lib/libc++.so.1" Size:1460461 Modified:Mon Sep 8 20:01:17 2014

How to pass functions defined in a class as arguments to functions?

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.

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;
}

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;
}