How do you convert a string holding a date from DD-MM-YYYY to MM-DD-YYYY - arrays

I have been working on this for about a week and for some reason I just can't get past it. I am getting an out of range error when I am searching the elements of the array, and attempt to move the characters I need to a need array.
void showFileDateCleansed(string first[], string last[], string birthday[])
{
string tempHoldDD[10];
string tempHoldMM[10];
/*
The stuff below is working so Ijust commented it out until I figure out the isssue I am having with the dates
for (int i = 0; i < 6; i++)
{
first[i].at(0) = toupper(first[i].at(0));
last[i].at(0) = toupper(last[i].at(0));
}
for (int i = 0; i < 10; i++)
{
cout << first[i] << " ";
cout << last[i] << "\n";
}*/
int d = 0; //Im using this to keep track of whether I have passed the delimiter in the text file "-"
bool done = false;
for (int i = 0; i < 10; i++)
{
done = false;
int c = 0;//this is used for the character within the element of the array, it increments at the bottom so that it moves to the next character.
while (done != true)
{
// <TK> Check for invalid character
if (c == 0)
{
std::cout << "Invalid character at index: " << i << std::endl;
}
if (birthday[i].at(c) == '-')
{
d += 1;
done = true;
}
else
{
switch (d)
{
case 0:
{
// Try catch to prevent the out of range exception from crashing.
//try
//{
// Debug
std::cout << "C: " << c << std::endl;
// create a temporary variable for the value.
char temp = birthday[i].at(c);
tempHoldDD[i].at(c) = temp;
//}
/*catch (std::out_of_range const& exc)
{
std::cout << exc.what() << '\n';
}*/
//cout << tempHoldMM[c] << "\n";
}
case 1:
{
// Try catch to prevent the out of range exception from crashing.
try
{
// Debug
std::cout << "C: " << c << std::endl;
// create a temporary variable for the value.
char temp = tempHoldMM[i].at(c);
birthday[i].at(c) = temp;
}
catch (std::out_of_range const& exc)
{
std::cout << exc.what() << '\n';
}
//cout << tempHoldMM[c] << "\n";
c += 1;
break;
}
}
}
}
}

Your case 1 in your switch statement doesn't have a break statement, so it will fall through to case 2, where c is incremented. Could that make c get out of range too fast?

Related

Constructor Operator << Device and Test Dynamic Array

#include iostream
#include cmath
#include fstream
#include cstdlib
#include string
using namespace std;
class Device {//Input and store Device Description and Serial Numbers
protected:
static string serial_number;
static string device_description;
public:
Device() {
serial_number = ("6DCMQ32");
device_description = ("TheDell");
}
Device(string s, string d) {
serial_number = s;
device_description = d;
}
};
string Device::device_description;
string Device::serial_number;
class Test {//Input and store Test Description, recent day, and month;
Calculate the next day
protected:
static string Test_Description;
static int recent_month, recent_day, recent_year, new_month;
static int nmonth, next_month, next_day, next_year, max_day;
public:
Test() {
Test_Description = ("Virtual");
}
static void getMonth() {//Calculates the next/new month
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12) {
cout << "The next Date: " << new_month << " / ";
}
else {
cout << "The next Date: " << next_month << " / ";
}
}
static void getDay() { //Calculates day of next month
if (new_month == 4 || new_month == 6 || new_month == 9 || new_month == 11) {
max_day = 30;
}
else if (new_month == 2) {
max_day = 29;
}
else {
max_day = 31;
}
if (recent_day > max_day) {
cout << max_day << " / ";
}
else {
cout << recent_day << " / ";
}
}
static void getYear() {// Calculate the year of next month
next_year = recent_year + next_month;
if (next_year >= 12) {
cout << recent_year + (next_month / 12) << endl;
}
else {
cout << next_year << endl;
}
}
static void getDate() {// Collects the output of each element of next date
Test::getMonth(), Test::getDay(), Test::getYear();
}
};
string Test::Test_Description;
int Test::recent_month;
int Test::recent_day;
int Test::recent_year;
int Test::new_month;
int Test::nmonth;
int Test::next_month;
int Test::next_day;
int Test::next_year;
int Test::max_day;
class Lab : public Device, public Test {
protected:
static int n;
public:
friend istream & operator>>(istream & in, Lab & lab) {// Inputs
cout << "Enter Device Desciption and Serial Number: ";
getline(in, device_description);
getline(in, serial_number);
cout << "Enter Test Desciption: ";
getline(in, Test_Description);
cout << "Enter the Number of months: ";
in >> nmonth;
cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
in >> recent_month >> recent_day >> recent_year;
return in;
}
friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs
everything in Device Class
out << Lab::device_description << endl;
out << Lab::serial_number << endl;
out << Lab::Test_Description << endl;
getDate();
return out;
}
static void getN() {
cout << "Enter the number of devices: ";
cin >> n;
}
static void getWrite() {
Lab *obj = new Lab[n];
if (obj == 0) {
cout << "Memory Error";
exit(1);
}
for (int i = 0; i<n; i++) {
cin >> obj[i];
cout << endl;
}
ofstream myfile("Device.txt");
myfile.write((char *)obj, n * sizeof(Lab));
delete[] obj;
}
static void getRead() {
ifstream file2("Device.txt");
Lab *obj2 = new Lab[n];
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
/*void getSearch(){
}*/
};
int Lab::n;
void main() {
Lab L;
L.getN();
L.getWrite();
L.getRead();
system("pause");
}
The Output I get is TheDell 6DCMQ32, Virtual when I entered my inputs. The date is correct the only problem is the Device Description, Serial Number, and Test Device.
Problem with Operator << in File i/o reading where it outputs the values in the Constructor
Purpose: is to enter the number of months for the next test date of device with input of serial number,
Device Description, Test Description, recent date, and the number of months of two tests. At the end the
program must be searched by having the user to input the serial number and the next date, if these two are
valid everything in the device is listed out.
Short of writing your application, I will do my best to give you some direction.
#include <iostream> // Note the '<' and '>' this is to specify is a language provided include
// More includes with the same issue...
using namespace std; // this is general considered bad=practice see https://stackoverflow.com/a/1452738/8480874 for details
//Input and store Device Description and Serial Numbers
class Device
{ // Notice the white space makes it easier to read...
protected:
//static string serial_number; // declaring this static means _EVERY_ device will have the same serial number
//static string device_description; // same as above
string serialNumber;
string deviceDesc;
public:
Device() : serialNumber("6DCMQ32"), deviceDesc("TheDell")
{
//serial_number = ("6DCMQ32"); // Not the best place for initialization
//device_description = ("TheDell"); // Not the best place for initialization
}
//Device(string s, string d) // you never actually use this
//{
// serial_number = s;
// device_description = d;
//}
};
//string Device::device_description; // This is a sign that you variable will be shared between everyone - not required if you remove the static
//string Device::serial_number; // This is a sign that you variable will be shared between everyone - not required if you remove the static
// This suffers from the same probles as the `class device` above
class Test
{
// Lots of stuff was here just trying to short the answer....
// Mostly has the same culprits mentions for the device
// This is one of the fucntions which gets called when you are trying to "save" the info to a file
static void getMonth(/* ostream & out */) // you need this as a paramater
{
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12)
{
// This function has no idea is needs to redirect the out put to a file...
// its only outputting to the standard console
cout << "The next Date: " << new_month << " / ";
}
else
{
//cout << "The next Date: " << next_month << " / ";
// using the new parameter in comments
// you can now save to your file
out << /*"The next Date: " <<*/ next_month << " / "; // no I comment out your extra message since you file reading does not look for that
}
}
};
// Again we have the same general misuse of C++ ( please keep learning! hopefully I am point you in the right direction )
class Lab : public Device, public Test
{
protected:
static int n;
public:
friend istream & operator>>(istream & in, Lab & lab)
{
// Inputs
cout << "Enter Device Desciption and Serial Number: ";
getline(in, device_description);
getline(in, serial_number);
cout << "Enter Test Desciption: ";
getline(in, Test_Description);
cout << "Enter the Number of months: ";
in >> nmonth;
cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
in >> recent_month >> recent_day >> recent_year;
return in;
}
friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs
everything in Device Class
out << Lab::device_description << endl;
out << Lab::serial_number << endl;
out << Lab::Test_Description << endl;
// Here you should pass the output pipe
getDate(/* out */);
return out;
}
static void getN() {
cout << "Enter the number of devices: ";
cin >> n;
}
static void getWrite()
{
// there's no real need to be using a pointer or memory allocation
//Lab *obj = new Lab[n];
// you can simply use
Lab obj[n];
//if (obj == 0)
//{
// cout << "Memory Error";
// exit(1);
//}
for (int i = 0; i < n; i++)
{
cin >> obj[i];
cout << endl;
}
ofstream myfile("Device.txt");
//myfile.write((char *)obj, n * sizeof(Lab)); // I've never tried writting an object's memory as a char* to file
// usually I like to generate a human readable output
std::string objBuffer = obj.getSaveBuffer(); // you will need to implement this `getSaveBuffer()` functions
myfile << objBuffer; // This can save lots of different value types for you! see http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
//delete[] obj; // since there is no more new; we dont need a delete!
}
// The logic of what you read suffers the same general issues as the write.
// Also what/how you read is very far from the save so I can't venture into any solutions
// I'm hoping this will kick start you to figuring it out on your own =)
static void getRead() {
ifstream file2("Device.txt");
Lab *obj2 = new Lab[n];
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
/*void getSearch(){
}*/
};
int Lab::n;
// A program that runs should always return a numeric result indicating success or failure
//void main() {
int main()
{
Lab L; // Since everything in all your classes is static this didnt really add anything
// you done need an object if the object contains nothing
L.getN();
L.getWrite();
L.getRead();
system("pause"); // this is also bad practice, see https://stackoverflow.com/a/1107717/8480874
// I personally like `getchar()` because it's easy and quick
}

How to make Account user generator c++ (problem: making array of objects and dynamically expanding it)

I'm 15 and I moved to Sweden. I don't have time to study c++, because I need to learn the language, but later (few months probably), I'll continue with 300 page book (it's 500, but in 3 years I learned (through YouTube mostly) about 200 pages of that book). I'm not willing to learn right now about vector, so if you give me answer with vector, if you could explain to me how it works, or give me link where it "simply" explains vector.
Anyway, being all said and done, here's my problem:
I'm building in c++ program that on the start, it has 1 object(NAobj) where it will store your name and age, and then you can select option to continue to create another account, and so on. When you first run that program it makes Aobj array object and expands it every time when you want create new account. But I just can't get it to work.
I found how I can expand array of objects, but, as I said, it's not realy working...
How to expand an array dynamically in C++? {like in vector }
Here's my code:
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int AccountFinder(string findName, string accountNames);
class Account
{
public:
Account()
{
}
~Account()
{
}
string name = "-ERROR NAME-";
int age = 18;
private:
};
Account NAobj;
int Asize = 1;
string AName;
string Iname;
int ASelector;
int main() {
Account *Aobj = new Account[Asize];
while (Iname.empty()) {
cout << "Name: #";
getline(cin, Iname);
if (Iname.empty())
{
cout << '\a' << endl;
MessageBox(NULL, "No name found\nPlease enter name", "Error 01", MB_ICONERROR);
system("cls");
}
else if (Iname == " ") {
cout << '\a' << endl;
MessageBox(NULL, "Non suported name", "Error 02", MB_ICONERROR);
system("cls");
Iname.clear();
}
else {
string a;
cout << "Crete account? y\\n #";
getline(cin, a);
if (a == "y") {
AName += Iname;
////generatin account
NAobj.name = Iname;
Account *TAobj = new Account[Asize];
if (Asize == 1) {
copy(Aobj, Aobj + Asize - 1, TAobj);
delete[] Aobj;
Aobj = TAobj;
copy(Aobj, Aobj + Asize - 1, &NAobj);
}
else {
copy(Aobj, Aobj + Asize - 1, TAobj);
copy(&NAobj, &NAobj, (TAobj + Asize - 1));
delete[] Aobj;
Aobj = TAobj;
}
////
AName += " ";
cout << "Want to continue? y\\n #";
getline(cin, a);
if (a == "y") {
system("cls");
Iname.clear();
}
else {
AName.resize(AName.size() - 1);
}
Asize++;
}
else {
cout << "Want to continue? y\\n #";
getline(cin, a);
if (a == "y") {
system("cls");
Iname.clear();
}
else {
AName.resize(AName.size() - 1);
}
}
}
}
Iname.clear();
cout << ">" << AName << "<" << endl;
cout << AName << endl;
string name;
cin >> name;
int ANumber = AccountFinder(name, AName);
if(ANumber != -1)
cout << ANumber << endl;
else
cout << "no account name: >" << name << "< found" << endl;*/
cout << endl;
system("pause");
}
int AccountFinder(string findName, string accountNames) {
string compareName;
int Account = 0;
bool space = TRUE;
int startPos = 0;
int a = 0;
while (1) {
while (1) {
if (accountNames.at(a) == ' ') {
break;
}
else
a++;
if (a == accountNames.size() - 1)
return -1;
}
compareName.resize(a - startPos);
for (int b = startPos; b < a; b++) {
compareName.at(b - startPos) = accountNames.at(b);
}
if (findName == compareName) {
return Account;
}
a++;
startPos = a;
if (Account > 0) {
1;
}
Account++;
}
}
Asize - Account Size (indicate size of array)
Aobj - Account Object (array of account objects)
NAobj - New Account Object ("temporary" storage for account name, probably won't use that later...)
Program Output
p.s.
Sorry for my bad english and i know my program is a mess, but i'm lazy to tidy it up.
The simplest solution to your problem is using a vector to store references to objects of the class. I recommend going to the "trouble" of learning how to use vectors. They are not as difficult to understand as you might fear, and are definitely one of the simplest dynamic data structures.
This might help: https://www.geeksforgeeks.org/vector-in-cpp-stl/

C++ How to Increment Int Variable From String Array Element

I'm wondering if there is a way to increment an int variable when a specific string array element is called? I'm working on a project for fun and have run into a roadblock. The goal of my project is to have a program that determines what genres of electronic music the user likes. The program will present two DJ's and ask the user which one they prefer or allow them to select neither. Each DJ will have up to three genres that they mainly specialize in, and I have created int variables for each (with all being set to 0). Once a user selects a DJ, I want points to be assigned to each genre variable in which the DJ is associated with. I'm unsure of how to set up this rule as everything I have attempted so far has failed (two example attempts are commented out in the code). Eventually my plan is to develop logic to have the DJ's randomly selected, however I need to have the genre tally allocation set up first. Is there any way this can be done? Any help would be greatly appreciated. Cheers!
###include "stdafx.h"
###include < iostream>
###include < iomanip>
###include < string>
###include < array>
###using namespace std;
int main()
{
cout << "Hello! This program is designed to figure out what Electronic Music you like based on artists presented and the answers you choose...\n" << endl;
cout << "When you are ready to begin press \"Enter\"..." << endl;
getchar();
int bigRoom = 0;
int deepHouse = 0;
int drumBass = 0;
int dubstep = 0;
int electroHouse = 0;
int futureHouse = 0;
int hardDance = 0;
int house = 0;
int progressiveHouse = 0;
int techno = 0;
int trance = 0;
int trap = 0;
string textArray[5]{ "DeadMau5", "Armin Van Buuren", "Avicii", "Ferry Corsten", "Kaskade"};
string answer;
cout << "Select the DJ you prefer by number. Otherwise select 3 if you don't know them. " << endl; //Haven't coded option 3 yet.
cout << "1 - " << textArray[1] << endl;
cout << "2 - " << textArray[2] << endl;
cin >> answer;
/*
if (textArray[1]) {
++trance;
}
for (textArray[1]) {
++trance;
}
*/
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
}
//cout << trance << endl;
}
You can increment each tally once the user has selected a DJ:
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
++trance;
// ++ ohter genres you want to increment
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
++trance;
// ++ ohter genres you want to increment
}

Boost C++ Regex Example Compile Error

I'm having an extremely frustrating time trying to get the Boost regex library to behave itself in XCode 8.
I've finally managed to sort the includes out, now I'm hitting compiler errors when attempting to run the following regex example from Boost's library documentation here.
The code is as follows:
void print_captures(const std::string& regx, const std::string& text)
{
boost::regex e(regx);
boost::smatch what;
std::cout << "Expression: \"" << regx << "\"\n";
std::cout << "Text: \"" << text << "\"\n";
if(boost::regex_match(text, what, e, boost::match_extra))
{
unsigned i, j;
std::cout << "** Match found **\n Sub-Expressions:\n";
for(i = 0; i < what.size(); ++i)
std::cout << " $" << i << " = \"" << what[i] << "\"\n";
std::cout << " Captures:\n";
for(i = 0; i < what.size(); ++i)
// compiler error in line above
{
std::cout << " $" << i << " = {";
for(j = 0; j < what.captures(i).size(); ++j)
// compiler erro in line above
{
if(j)
std::cout << ", ";
else
std::cout << " ";
std::cout << "\"" << what.captures(i)[j] << "\"";
}
std::cout << " }\n";
}
}
else
{
std::cout << "** No Match found **\n";
}
}
int main(int , char* [])
{
print_captures("(([[:lower:]]+)|([[:upper:]]+))+", "aBBcccDDDDDeeeeeeee");
print_captures("(.*)bar|(.*)bah", "abcbar");
print_captures("(.*)bar|(.*)bah", "abcbah");
print_captures("^(?:(\\w+)|(?>\\W+))*$",
"now is the time for all good men to come to the aid of the party");
return 0;
}
I'm getting two errors at the points indicated in the block above that both read:
No member named 'captures' in 'boost::match_results<std::__1::__wrap_iter<const char *>, std::__1::allocator<boost::sub_match<std::__1::__wrap_iter<const char *> > > >'
Apologies in advance if this question has been answered elsewhere.
Any idea how I can fix this?

Finding the max and min values in array of five times

I'm supposed to find the minimum and maximum values in the array, but I can't seem to figure out why the answers aren't correct. For example if I entered "1 2 3 4 5" as my five times, it told me 1 was my maximum and 0 was the minimum. For some reason, whatever the first number is, it calls it the max and it also assigns 0 as the min.
#include <iostream>
using namespace std;
int find_distance(int j); //a function that returns a distance based on the choice j
int intmax, intmin;
int main( )
{
int i =0;
int distance[6];
double data[6][5];
for(int j = 0; j < 6; j++)
{
distance[j] = find_distance(j);
cout << "\nEnter 5 of your best running times for \n " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
cout << "Enter a time \n"; cin >> data[j][i];
}
}
cout << "Here is your best 5 times: ";
for(int j = 0; j < 6; j++)
{
cout << "\nDistance : " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
system ("pause");
cout << data[j][i] << "\t"; } cout << endl;
if (data[j][i] < intmin)
intmin = data[j][i];
else if (data[j][i] > intmax)
intmax = data[j][i];
cout << "The maximum time is: " << intmax << endl;
cout << "The minimum time is: "<< intmin << endl;
}
return 0;
}
int find_distance(int j)
{
switch (j)
{ case 0: // 100 meter
return 100;
break;
case 1: // 150 meter
return 150;
break;
case 2: // 200 meter
return 200;
break;
case 3: // 400 meter
return 400;
break;
case 4: // 500 meter
return 800;
break;
default: // 1600 meter
return 1600;
}
}
The minimum value is 0 because when you initialize intmin, it is set to 0 by default. You never enter a negative time, so in your comparisons it is always less than the compared value.
The maximum value is off because your for loop ends in an odd place and the comparison code is improperly executed. Change this code:
for(int j = 0; j < 6; j++)
{
cout << "\nDistance : " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
system ("pause");
cout << data[j][i] << "\t"; } cout << endl; //why does the for loop end here?
if (data[j][i] < intmin)
intmin = data[j][i];
else if (data[j][i] > intmax)
intmax = data[j][i];
//move the end bracket to this line and it should work
cout << "The maximum time is: " << intmax << endl;
cout << "The minimum time is: "<< intmin << endl;
}
Just to practice:
#include <iostream>
#include <algorithm>
#include <string>
#include <boost/regex.hpp>
int main () {
using namespace std;
string input;
boost::regex re("-?\\d+");
vector<int> integers;
cout << "enter sequence of integers: ";
getline(cin, input);
boost::sregex_token_iterator begin(input.begin(), input.end(), re, 0);
boost::sregex_token_iterator end;
while (begin != end) {
integers.push_back(stoi(*begin));
++begin;
}
if (integers.size()) {
auto pair = minmax_element(integers.begin(), integers.end());
cout << "min: " << *pair.first << " max: " << *pair.second << endl;
} else {
cout << "you didn't enter any integers." << endl;
}
return 0;
}
This is how to compile and to run:
$ g++ -o lab_2 -std=c++11 -lboost_regex lab_2.cpp
$ ./lab_2
$ enter sequence of integers: -10 34 75 101 2 43
$ min: -10 max: 101
Requires boost installed because STL regular expressions aren't functional yet.

Resources