Converting date format? - c++

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
// declares variables
string dayow;
string month;
string day;
string year;
int main()
{
cout << "Pick you day of the week (ex: Monday-Sunday)" << endl;
getline(cin, dayow);
cout << " " << endl;
cout << "Pick your month (ex: January-December)" << endl;
getline(cin, month);
cout << " " << endl;
cout << "Pick your day of the month (ex: 1-31)" << endl;
getline(cin, day);
cout << " " << endl;
cout << "Pick your year" << endl;
getline(cin, year);
cout << " " << endl;
cout << "This is your date.." << endl;
cout << dayow << ", " << month << " " << day << ", " << year << "." << endl;
cout << " " << endl;
cout << "Here are the 3 formats to display your date.." << endl;
cout << " " << endl;
cout << "1. " << month << " " << day << " was a " << dayow << " in " << year << endl;
cout << " " << endl;
std::string str = dayow;
std::string str1 = str.substr(0, 3);
std::string str = month;
std::string str2 = str.substr(0, 2);
std::string str = day;
std::string str3 = str.substr(0, 2);
std::string str = year;
std::string str4 = str.substr(0, 4);
std::cout << str1 << ", " << str2 << " " << str3 << " '" << str4 << endl;
return 0;
}
So what i'm trying to do here is get the user to input ex: Tuesday, March 22, 2012, then have 2 results come out. 1st being "January 1 was a Tuesday in 2012", that is fine as it is. Where the problem lies is the second result where I want "Tue, Mar 22, 2012" but the problem is on line 46 - 53, all of the strings are connecting to the first std:string str = dayow; so the output turns into TueTuTuTues!
Can anyone help?? thanks!
EDIT : Sorry if this is a noob questions :/ really new to coding!

Try this one: (some changes of your code)
#include <iomanip>
#include<iostream> // **add this header file**
#include <string>
#include <fstream>
using namespace std;
// declares variables
string dayow;
string month;
string day;
string year;
int main()
{
cout << "Pick you day of the week (ex: Monday-Sunday)" << endl;
getline(cin, dayow);
cout << " " << endl;
cout << "Pick your month (ex: January-December)" << endl;
getline(cin, month);
cout << " " << endl;
cout << "Pick your day of the month (ex: 1-31)" << endl;
getline(cin, day);
cout << " " << endl;
cout << "Pick your year" << endl;
getline(cin, year);
cout << " " << endl;
cout << "This is your date.." << endl;
cout << dayow << ", " << month << " " << day << ", " << year << "." << endl;
cout << " " << endl;
cout << "Here are the 3 formats to display your date.." << endl;
cout << " " << endl;
cout << "1. " << month << " " << day << " was a " << dayow << " in " << year << endl;
cout << " " << endl;
// **changes start here**
string str1 = dayow.substr(0, 3);
string str2 = month.substr(0, 3);
string str3 = day.substr(0, 2);
string str4 = year.substr(0, 4);
cout << str1 << ", " << str2 << " " << str3 << " ," << str4 << endl;
return 0;
}

Which compiler do you use? Your program shouldn't compile.
Add #include <iostream>
You cann't define few variables with same name C++.
So replace
std::string str = dayow;
std::string str1 = str.substr(0, 3);
std::string str = month;
std::string str2 = str.substr(0, 2);
std::string str = day;
std::string str3 = str.substr(0, 2);
std::string str = year;
std::string str4 = str.substr(0, 4);
with
std::string str1 = dayow.substr(0, 3);
std::string str2 = month.substr(0, 2);
std::string str3 = day.substr(0, 2);
std::string str4 = year.substr(0, 4);

change this part:
std::string str = dayow;
std::string str1 = str.substr(0, 3);
std::string str = month;
std::string str2 = str.substr(0, 2);
std::string str = day;
std::string str3 = str.substr(0, 2);
std::string str = year;
std::string str4 = str.substr(0, 4);
to:
std::string str = dayow;
std::string str1 = str.substr(0, 3);
std::string stra = month;
std::string str2 = stra.substr(0, 3);
std::string strb = day;
std::string str3 = strb.substr(0, 2);
std::string strc = year;
std::string str4 = strc.substr(0, 4);
problem was you had same variable name for day,month and year

Related

Adding Count to Qt Framework on buttonclick

I have a button that appends from lineEdit to a *.txt file.
I want to know if there is something i can do to get something like this :
Student N°1:
FirstName : -----
LastName: -----
Age: -----
Student N°2:
FirstName : -----
LastName: -----
Age: -----
I want that everytime my program checks last student number (the one inserted before) and adds +1 to the one i'm trying to append.
QFilefile("***");
if (file.open(QFile::Append)) {
QTextStream out(&file);
out <<"Student Num:"<<"\n";
out <<"Name:" << ui->lineEdit->text()<<"\n";
The File I have Now :
FirstName :
LastName :
Age :
FirstName :
LastName :
Age :
Desired Output :
Student N°1
FirstName :
LastName :
Age :
Student N°2
FirstName :
LastName :
Age :
I want that N°(var) to be +1 everytime i hit save button
this might help you along.
now you only need to make a method / function to update a specific "student" datatype and write back to file.
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <iostream>
#include <ctime>
using namespace std;
typedef std::vector<string> Vector;
struct Student
{
Student () : firstName(""), lastName(""), age(0){};
Student (const std::string& firstname, const std::string& lastname, unsigned short age) : firstName(firstname), lastName(lastname), age(age){};
std::string firstName;
std::string lastName;
unsigned short age;
};
typedef std::vector<Student> studentVector;
void readReadFile(string &fileName, studentVector &array){
std::ifstream file(fileName);
if(file.fail()){
//File does not exist code here
std::cout << "File doesn't exist." << endl;
return;
}
else{
int counter = 0;
std::string str;
string studentName = "";
string studentLastName = "";
int age = 0;
while (std::getline(file, str)) {
if(counter == 0){
//++counter;
std::string strName="FirstName :";
std::string str2 = strName.substr (0,11);
//std::cout << "FirstName : " << str2 << endl;
if(str.length() < 11){
return; // no name present
}
std::string::size_type posName = str.find(str2);
//std::cout << "size_t: " << posName << endl;
if (posName != string::npos) {
//.. found.
std::string str3 = str.substr (12, str.length());
std::cout << "Name: " << str3 << endl;
//std::cout << "size_t: " << posName << endl;
std::cout << "found Name" << endl;
studentName = str3;
}
}
if(counter == 1){
//++counter;
std::string strName="LastName :";
std::string str2 = strName.substr (0,10);
//std::cout << "LastName: " << str2 << "length: " << str2.length() << endl;
if(str.length() < 10){
return; // no lastname present
}
std::string::size_type posLastName = str.find(str2);
//std::cout << "size_t: " << posName << endl;
if (posLastName != string::npos) {
//.. found.
std::string str3 = str.substr (11, str.length());
std::cout << "LastName: " << str3 << endl;
//std::cout << "posLastName : " << posLastName << endl;
std::cout << "found lastName" << endl;
studentLastName = str3;
}
}
if(counter == 2){
//++counter;
std::string strName="Age :";
std::string str2 = strName.substr (0,5);
//std::cout << "Age: " << str2 << endl;
if(str.length() < 5){
return; // no age present
}
std::string::size_type posAge = str.find(str2);
//std::cout << "size_t: " << posName << endl;
if (posAge != string::npos) {
//.. found.
std::string str3 = str.substr (6, str.length());
std::cout << "Age: " << str3 << endl;
//std::cout << "posAge : " << posAge << endl;
std::cout << "found age" << endl;
age = std::stoi(str3);
}
}
++counter;
std::string::size_type posName = str.find("---");
if (posName != string::npos) {
counter = 0;
Student test(studentName, studentLastName, age);
array.push_back(test);
std::cout << "------------------" << endl;
// std::cout << "empty" << std::endl; // white line
}
}
file.close();
}
}
void appendstuff(Student data, studentVector &array){
array.push_back(data);
}
void write_students_backtofile(string &fileName, studentVector &array){
// https://stackoverflow.com/questions/17032970/clear-data-inside-text-file-in-c
std::ofstream myfile;
myfile.open(fileName, std::ofstream::out | std::ofstream::trunc);
//myfile.close();
// write vector back to file
//ofstream myfile;
//myfile.open (fileName);
for(auto& i : array){
myfile << "FirstName : " << i.lastName << "\n";
myfile << "LastName : " << i.firstName << "\n";
myfile << "Age : " << i.age << "\n";
//myfile << "\n"; // white line
myfile << "---\n"; // white line
}
myfile.close();
array.clear();
}
int main(){
std::clock_t start;
double duration;
start = std::clock();
studentVector array;
string fileName = "input.txt";
readReadFile(fileName, array);
Student test2("Frodo", "Baggins", 66);
Student test3("Gandalf", "the Grey", 254);
Student test4("Saruman", "the White", 450);
appendstuff(test2, array);
appendstuff(test3, array);
appendstuff(test4, array);
std::cout << "----------------------------------" << endl;
for(auto& i : array){
std::cout << i.lastName << " " << i.firstName << " " << i.age << endl;
}
string testFile = "test.txt"; // for testing.
write_students_backtofile(fileName, array);
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout<<"printf: "<< duration << " seconds" << '\n';
return 0;
}

c++ ostream output with setw

I have an output file name out
using the below code to add a string to the text file:
string foo = "Hello, foo";
out << foo;
How can I customize a string to input into out file
adding string and numbers with a specific width using setw(7)
Your name is:AName you are 18
Your name is:foo you are 30
with variable name holding the name and variable age holding the age
how can I make this code works
out<< ("Your name is :"+ setw(7)+ name +" you are " + age);
You could try something like this:
std::string name = "AName";
unsigned int age = 18;
out << "Your name is:" << setw(7) << name << "you are " << age << "\n";
If you have a struct and database, this might be:
struct Name_Age
{
std::string name;
unsigned int age;
};
int main()
{
std::vector<Name_Age> database;
Name_Age record;
record.name = "AName"; record.age = 18;
database.push_back(record);
record.name = "foo"; record.age = 30;
database.push_back(record);
for (size_t index = 0; index < database.size(); ++index)
{
cout << "Your name is:" << setw(7) << database[index].name
<< "you are " << database[index].age << "\n";
}
return 0;
}
It is just as simple as
std::out << "Your name is :" << std::setw(7) << std::left << name << " you are " << age;
setw does not return a string that you can concatenate. It returns an unspecified type that can be passed to operator << of an output stream.

Assertion failure when reading from a map

int main(){
//Date Variables
int day;
int month;
int year;
string comName;
string temp;
string temp2;
//Time Variables
int hours;
int minutes;
int seconds;
string amPm;
ofstream ofstr("output.csv");
float price = 0.00;
int volume;
float value = 0.00;
float runningVol = 0.00;
float runningVal = 0.00;
float runningPrice = 0.00;
string condition;
string fileName;
string tempCName;
string compDate;
ifstream inFile;
ifstream compFile;
ifstream mainFile;
map<string, Vector <Share>> stlMap;
inFile.open("code_index.txt");
if(inFile.is_open()){
while(!inFile.eof()){
getline(inFile,tempCName);
cout << "read next line in code_index" << endl;
comName = tempCName+"\\sales_index.txt";
cout << "Company name to open is: " << comName << endl;
compFile.open(comName);
if(compFile.is_open()){
while(!compFile.eof()){
getline(compFile,fileName);
cout << "Read the fileName: " << fileName << endl;
fileName = tempCName+"\\"+fileName;
mainFile.open(fileName);
if(mainFile.is_open()){
Vector <Share> myVec;
while(!mainFile.eof()){
compDate = "";
cout << "Stored all the variables" << endl;
//Getting and storing the Date
getline(mainFile,temp2,'/');
day = atoi(temp2.c_str());
getline(mainFile,temp2,'/');
month = atoi(temp2.c_str());
getline(mainFile,temp2,' ');
year = atoi(temp2.c_str());
//cout << "date = " << day << "mo = " << month << "yr = " << year;
//Date d;
Date d(day,month,year); //Sending them to the Date class using the parameterized constructor
compDate = tempCName + "_" + d.returnDate();
//cout << "Date is: "<< compDate << endl;
cout << compDate << endl;
// Getting and storing the time variable
getline(mainFile,temp2,':');
hours = atoi(temp2.c_str());
getline(mainFile,temp2,':');
minutes = atoi(temp2.c_str());
getline(mainFile,temp2, ' ');
seconds = atoi(temp2.c_str());
getline(mainFile,temp2,',');
amPm = temp2;
//Time t;
Time t(hours,minutes,seconds,amPm);
//cout << "Hours = " << hours << "minutes = " << minutes << "seconds = " << seconds << " " << amPm;
getline(mainFile,temp2,',');
price = atof(temp2.c_str());
//cout << price;
getline(mainFile,temp2,',');
volume = atoi(temp2.c_str());
getline(mainFile,temp2,',');
value = atof(temp2.c_str());
getline(mainFile,temp2,'\n');
condition = temp2;
Share s(price,volume,value,d,t);
myVec.push_back(s);
}
stlMap[compDate] = myVec;
mainFile.close();
}
else{ cout << "Specified day file not found";}
}
compFile.close();
}
else{cout << "Specified company folder not found / sales_indexfile not found" << endl;}
}
inFile.close();
}
else
{cout << "code_index.txt not found. Please make sure the file exists";}
for(map<string, Vector <Share>>::iterator itr = stlMap.begin();itr!=stlMap.end() ;itr++ )
{
cout << "map values\n";
//cout << itr->first << endl;
//cout << itr->second.length() << endl;
}
int iii = 0;
cin >> iii;
return 0;
}
I have my own templated vector, but this for loop to print from the map causes an assertion error, help please?
Also, if I comment out the bit where I enter into the map, the error is gone.
which makes me say, the vector isnt the cause of the issue.

Simple c++ inFile and setup

The program works my only problem is that I don't know how to line up the output. When ran using the .txt file it prints the names, boxes, and name of cookies but not aligned. Also, I have to calculate the amount due for each person and display it, but i only can figure out how to do the total. Thanks for help
#include <iomanip>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream inFile;
//Declare Variables
string firstName;
string cookieName;
int boxesSold;
int numCustomers = 0;
double amountDue;
int totalCustomers;
int totalBoxesSold = 0;
double totalAmount = 0;
cout << "Girl Scout Cookies" << endl;
cout << "Created By Aaron Roberts" << endl;
inFile.open("cookie.txt");
if(inFile)
{
cout << "Customer Number Cookie" << endl;
cout << "Name Of Boxes Name" << endl;
while(inFile >>firstName>>boxesSold>>cookieName)
{
totalBoxesSold += boxesSold;
totalAmount += boxesSold * 3.50;
cout << setprecision(2) << fixed << showpoint;
cout << setw(2) << firstName
<< right << setw(7) << boxesSold
<< setw(20) << cookieName
<< endl;
numCustomers += 1;
}
cout << "\nNumber of Customers: "<< numCustomers << endl;
cout << "Total Boxes Sold: " << totalBoxesSold << endl;
cout << "Total Amount: $" << totalAmount << endl;
inFile.close();
}
else
{
cout << "Could not open file " << endl;
}
system("pause");
return 0;
}
Given you've allocated 12 characters in the header for the "Customer Name" and "Number Of Boxes" columns, you probably want to allocate 11 characters for their data, leaving one character for a trailing space.
For clarity and maintainability, I recommend you create constants for these:
int const name_column_width = 11;
int const boxes_column_width = 11;
Then you can write:
std::cout << std::setw(name_column_width) << std::left << "Customer" << ' '
<< std::setw(boxes_column_width) << std::left << "Number" << ' '
<< "Cookie"
<< std:: endl;
std::cout << std::setw(name_column_width) << std::left << "Name" << ' '
<< std::setw(boxes_column_width) << std::left << "Of Boxes" << ' '
<< "Name"
<< std:: endl;
while (inFile >> firstName >> boxesSold >> cookieName)
{
totalBoxesSold += boxesSold;
totalAmount += boxesSold * 3.50;
std::cout << std::setw(name_column_width) << std::left << firstName << ' '
<< std::setw(boxes_column_width) << std::right << boxesSold << ' '
<< cookieName
<< std::endl;
++numCustomers;
}
Resizing these columns then becomes a simple matter of changing the constant.

Seemingly simple issue with calling information from an array in C++

This seems like it should be easy, which is why it is driving me especially insane. Hopefully someone out there will see the problem right off. I'm just trying to build arrays from an array built from a user input. It seems to create an array that is bigger than the one I meant for it to. Here's the program:
int main()
{
ifstream inFile;
ofstream outFile;
int numReq, fileSize;
string lang, dash;
char fileName[40];
char confirm[10];
char confirm2[10];
int character;
char year[3];
char month[1];
char day[1];
char hour[1];
cout << "What file to process?" << endl;
cin >> fileName;
year[0] = fileName[14];
year[1] = fileName[15];
year[2] = fileName[16];
year[3] = fileName[17];
cout << "year = " << year << "." << endl;
month[0] = fileName[18];
month[1] = fileName[19];
cout << "month = " << month << "." << endl;
cout << "so I gotta know, what is..." << endl;
cout << "month[0]? " << month[0] << endl;
cout << "month[1]? " << month[1] << endl;
cout << "month[2]? " << month[2] << endl;
cout << "month[3]? " << month[3] << endl;
cout << "month[4]? " << month[4] << endl;
cout << "month[5]? " << month[5] << endl;
cout << "month[6]? " << month[6] << endl;
day[0] = fileName[20];
day[1] = fileName[21];
cout << "day = " << day << "." << endl;
hour[0] = fileName[23];
hour[1] = fileName[24];
cout << "hour = " << hour << "." << endl;
cout << "so, 'fileName[23]' is = " << fileName[23] << "?" << endl;
cin >> confirm;
cout << "So, the year is " << year << ", the month is " << month
<< ", the day is " << day << ", the hour is " << hour << "?" << endl;
cin >> confirm;
//cout << "Is this what you chose? " << fileName << endl;
//cin >> confirm;
//cout << "Which character to manipulate?" << endl;
//cin >> character;
//cout << "This one? " << fileName[character] << endl;
//cin >> confirm2;
inFile.open(fileName);
assert (!inFile.fail());
outFile.open("revisedPracticeFile1.txt");
outFile << fixed << showpoint; // I have no idea what this is...
outFile << setprecision(2); // .. or this for that matter.
cout << "Processing data" << endl;
inFile >> lang;
while (!inFile.eof() ){
if (lang.length() <= 2){
outFile << lang << " ";
// I should keep in mind, that, for whatever reason, it seemed like the
//item 'setw(6)' made the program work when I put it in, but didn't seem
//to make the program stop working when I took it out. Curious..
inFile >> dash >> numReq >> fileSize;
outFile << numReq << " " << fileSize << endl;
}
else{
inFile >> dash >> numReq >> fileSize;
cout << "took out " << lang << " " << numReq << " " << fileSize << endl;
}
inFile >> lang;
}
inFile.close();
//assert(!inFile.fail());
outFile.close();
return 0;
}
...And, this is what happens when I run the program:
What file to process?
projectcounts-20090101-010000
year = 2009.
month = 01009.
so I gotta know, what is...
month[0]? 0
month[1]? 1
month[2]? 0
month[3]? 0
month[4]? 9
month[5]?
month[6]?
day = 011009.
hour = 0111009.
so, 'fileName[23]' is = 0?
yes
So, the year is 1009, the month is 11009, the day is 111009, the hour is 0111009?
^C
... So what gives?
The syntax char year[3]; declares an array with 3 element. But, then you use it to store 4 elements. There are similar issues with your other arrays.
Also, you're using char arrays as strings. That's a C (not C++) way to do things. Of course you're allowed to do this if you want. But, these c-style strings use the convention that the last item is a zero.
Thus, if you wanted a C-style string to store the work 'foo', you could do it like this
char string[10]; // anything bigger than 3 works
string[0] = 'f';
string[1] = 'o';
string[2] = 'o';
string[3] = '\0'; // this zero tells functions like `printf` that the string has ended.
Without that last zero, functions like printf will just keep outputting memory locations until it happens upon a zero somewhere.
EDIT: Consider using c++ std::string for your string processing.