Adding Count to Qt Framework on buttonclick - c++

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

Related

Trying to run a count so I know when the last row of data is written so I can output a ']' instead of a ','

I want my output file to look like this:
However, no matter what I try, it looks like this:
I can't get my comma condition to work for the output. I've tried to use eof, counts, etc but I'm not really sure where to go.
I've tried looking at other posts, but I either can't find one linked, or I don't actually understand it.
#include <iostream>
#include <fstream> //ofstream declared in this header file
#include <string>
#include <sstream>
#include <vector>
using namespace std;
//Creates Structure For Columns
struct InputFile
{
string Date;
string Value;
string SignalStrength;
string Voltage;
};
int main()
{
ifstream input;
string Row;
string Column;
int count = 0;
int count2 = 0;
//Stores Data From Structure As Vector
vector<InputFile> InputDataStored;
input.open("Temperature.csv");
if (input.fail())
{
cerr << "File does not exist. Exiting" << endl; //cerr is cout for errors
return 1; //This could be used as an error code
}
if (!input)
{
cerr << "File could not be opened." << endl;
}
while (getline(input, Row)) //Remove top line output from sensor data when opened in Notepad
{
getline(input, Row); // read an entire row and store it in a string variable 'line'
stringstream ss{ Row }; // used for breaking words
vector<string> Columns; // creates a temporary vector of strings
while (getline(ss, Column, ',')) // read an entire row and store it in a string variable 'column'
{
Columns.push_back(Column); // add all the data of a row to the temporary vector
count++;
}
//InputFile t{}; // convert string to struct types
InputFile t;
if (Row.empty())
continue; // if it is a blank row, ignore it
else
t.Date = Columns[1];
t.Value = Columns[2];
t.SignalStrength = Columns[4];
t.Voltage = Columns[5];
InputDataStored.push_back(t); // add all the data of the new row to a vector
count2++;
cout << t.Date << " " << t.Value << " " << t.SignalStrength << " " << t.Voltage << endl;
}
input.close();
ofstream output;
output.open("SensorData.json");
if (!output)
{
cerr << "File could not be opened." << endl;
}
int JSONcount = 0;
output << "[";
for (InputFile t : InputDataStored)
{
JSONcount++;
output << "{" << endl;
output << "\"Date\": \"" << t.Date << "\"" << endl;
output << "\"Temperature\": " << t.Value << endl;
output << "\"Signal_strength\": " << t.SignalStrength << endl;
output << "\"Voltage\": " << t.Voltage << endl;
if (count2 >= JSONcount)
output << "}]" << endl;
else
output << "}," << endl;
}
output << JSONcount << endl;
output << count << endl;
output << count2;
output.close();
}
There are multiple mistakes in your code. Try something more like this instead:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
struct InputFile
{
string Date;
string Value;
string SignalStrength;
string Voltage;
};
int main()
{
vector<InputFile> InputDataStored;
string Line, Column;
int count = 0, count2 = 0;
ifstream input("Temperature.csv");
if (!input)
{
cerr << "Input file could not be opened. Exiting" << endl;
return 1;
}
getline(input, Line); //Remove top line output from sensor data when opened in Notepad
while (getline(input, Line)) // read an entire row and store it in a string variable 'line'
{
istringstream iss{ Line };
if (Line.empty())
continue;
vector<string> Columns;
while (getline(iss, Column, ','))
{
Columns.push_back(Column);
++count;
}
InputFile t;
t.Date = Columns[1];
t.Value = Columns[2];
t.SignalStrength = Columns[4];
t.Voltage = Columns[5];
InputDataStored.push_back(t);
++count2;
cout << t.Date << " " << t.Value << " " << t.SignalStrength << " " << t.Voltage << endl;
}
input.close();
ofstream output("SensorData.json");
if (!output)
{
cerr << "Output file could not be opened. Exiting" << endl;
return 1;
}
int JSONcount = 0;
output << "[";
for (const auto &t : InputDataStored)
{
++JSONcount;
if (JSONcount > 1)
output << "," << endl;
output << "{" << endl;
output << "\"Date\": \"" << t.Date << "\"" << endl;
output << "\"Temperature\": " << t.Value << endl;
output << "\"Signal_strength\": " << t.SignalStrength << endl;
output << "\"Voltage\": " << t.Voltage << endl;
output << "}";
}
output << "]" << endl;
output << JSONcount << endl;
output << count << endl;
output << count2;
output.close();
return 0;
}

How to access class object from a function

Ok So I have abit of a problem with my code that I cant seem to find the solution for. Im writing a program that will work like a phonebook for your phone. And everything that happens will be saved in a .txt file. So when the program starts it will always read from the same file and put that into class objects called "person" and then you will be able to edit/delete/add new contacts and then it gets rewriten to the file.
The problem im having right now is that I want to make more of the code into functions instead of having it all in the main folder. So as you can see from the two last functions, one should read from the file and the other should write to the file. What I want to do is to replace all the code in main() that has to do with readToFile and writeToFile. Also i would like to be able to put the writeToFile function after every case switch action like edit/delete/add. So that you dont have to choose to write to the file. It just does that automatically.
Can I somehow use pointers/references for this or how do i get access to the "person" objects in my functions.
First time asking a question here so feel free to educate me if i did something wrong.
Here is the code:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void printline(char, int);
bool name_valid(string);
class contact
{
public:
string fName, lName, adress, epost, mobileNo, birthday;
//initialize the contact by a default value
contact() : fName(""), lName(""), adress(""), epost(""), mobileNo(""), birthday("")
{}
// Write all contacts to the file.
bool writeToFile()
{
if (fName != "")
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1; //Success!!
}
else
{
cout << " Fail!" << endl;
return 0; //Fail!!
}
}
//Show all contacts
bool showAll()
{
if (fName != "")
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1; //Success!!
}
else
return 0; //Fail!!
}
// Search
bool Search(string search_word)
{
if (search_word == fName)
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1;
}
else
return 0;
}
// Check if a name exists or not
bool name_exists(string tname)
{
if (tname == fName)
return 1;
else
return 0;
}
// The contact object is initialized by valid values
bool addContact(string new_fName, string new_lName, string new_adress, string new_epost, string new_mobileNo, string new_birthday )
{
if (fName == "")
{
fName = new_fName;
lName = new_lName;
adress = new_adress;
epost = new_epost;
mobileNo = new_mobileNo;
birthday = new_birthday;
return 1; // Success !!
}
else
return 0; // Failure !!
}
//edits the contact details
bool edit(string);
bool erase(string new_name)
{
if (new_name == fName)
{
fName = "";
lName = "";
adress = "";
epost = "";
mobileNo = "";
birthday = "";
return 1;
}
else
return 0;
}
};
// Edits the contact
bool contact::edit(string name_check)
{
string new_fName, new_lName, new_adress, new_epost, new_mobileNo, new_birthday;
if (name_check == fName)
{
cin.ignore();
cin.clear();
cout << "Enter new first name: ";
getline(cin,new_fName);
cout << "Enter new lastname: ";
getline(cin,new_lName);
cout << "Enter new adress: ";
getline(cin,new_adress);
cout << "Enter new epost: ";
getline(cin,new_epost);
cout << "Enter new birthday: ";
getline(cin,new_birthday);
fName = new_fName;
lName = new_lName;
adress = new_adress;
epost = new_epost;
birthday = new_birthday;
return 1;
}
else
return 0;
}
int main()
{
contact person[100];
ifstream infile("Phonebook.txt");
string temp_fName, temp_lName, temp_adress, temp_epost, temp_mobilNo, temp_birthday;
int counter, choice, i;
bool flag;
bool cancel_flag;
// Read from file to contact person
string ignoreName, ignoreCell, ignoreAdress, ignoreEmail, ignoreBirthday;
string fileFirstname, fileLastname, fileCell, fileAdress, fileEmail, fileBirthday;
// Goes through the text file and put all the names in the contact class
while (!infile.eof())
{
getline(infile, ignoreName, ' ');
getline(infile, fileFirstname, ' ');
getline(infile, fileLastname);
getline(infile, ignoreCell, ' ');
getline(infile, fileCell);
getline(infile, ignoreAdress, ' ');
getline(infile, fileAdress);
getline(infile, ignoreEmail, ' ');
getline(infile, fileEmail);
getline(infile, ignoreBirthday, ' ');
getline(infile, fileBirthday);
// Check if the file is empty
if (!infile)
{
break;
}
for (i = 0; i < 100; i++)
if (person[i].addContact(fileFirstname, fileLastname, fileAdress, fileEmail, fileCell, fileBirthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
}
infile.close();
ofstream outfile("Phonebook.txt");
cout << "=========== Your Phonebook ==========" << endl;
do
{
cout << "\n\n";
printline('-', 25);
cout << "1. Add Contact" << endl
<< "2. Edit Contact" << endl
<< "3. Delete Contact" << endl
<< "4. Search" << endl
<< "5. Show All Contacts" << endl
<< "6. Write All Contacts To File." << endl
<< "0. Exit" << endl << endl
<< "Your choice... ";
cin >> choice;
system("cls");
printline('-', 20);
cancel_flag = 0;
flag = 0;
counter = 0;
switch (choice)
{
case 0:
return 0;
break;
// Adds a new contact
case 1:
cout << "Add New Contact\t\t\t\tpress - to cancel" << endl;
printline('-', 25);
counter = 0;
// Loop until correct contact info is untered
do
{
flag = 0;
if (counter)
cout << "Try again \t\t\t\tpress - to cancel" << endl;
//count how many times the do-while loop executes
counter++;
cin.ignore();
cin.clear();
cout << "First Name: ";
getline(cin, temp_fName);
cout << "Last Name: ";
getline(cin, temp_lName);
cout << "Adress: ";
getline(cin, temp_adress);
cout << "Email: ";
getline(cin, temp_epost);
cout << "Mobile Number: ";
getline(cin, temp_mobilNo);
cout << "Birthday: ";
getline(cin, temp_birthday);
if (temp_fName == "-")
{
cancel_flag = 1;
break;
}
for (i = 0; i < 100; i++)
{
if (person[i].name_exists(temp_fName))
{
cout << "The name you entered is already there"
"in the phonebook, entere a different name." << endl;
flag = 1;
break;
}
}
} while (!name_valid(temp_fName) || flag);
if (cancel_flag)
{
system("cls");
break;
}
//This loop adds the contact to the phonebook
for (i = 0; i < 100; i++)
if(person[i].addContact(temp_fName, temp_lName, temp_adress, temp_epost, temp_mobilNo, temp_birthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
if (!flag)
cout << "Memory full! Delete some contacts first." << endl;
break;
// Edits an existing contact
case 2:
cout << "Enter a contact name to edit \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
for (i = 0; i < 100; i++)
if (person[i].edit(temp_fName))
{
cout << "Edited Successfully!" << endl;
flag = 1;
break;
}
if (!flag)
cout << "Contact name not found!" << endl;
break;
//Delete a contact
case 3:
do
{
if (counter)
cout << "Try again" << endl;
counter++;
cout << "Enter a contact name to delete: \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
//Final Confirmation
for (i = 0; i < 100; i++)
if (person[i].name_exists(temp_fName))
{
flag = 1;
cout << "Are you sure you want to delete (1/0)" << endl;
int yes;
cin >> yes;
if (!yes)
{
system("cls");
cancel_flag = 1;
}
break;
}
if (!flag)
cout << "Contact name not found!" << endl;
if (cancel_flag)
break;
// This code deletes the contact
if (flag)
{
for (i = 0; i < 100; i++)
if (person[i].erase(temp_fName))
{
cout << "Deleted successfully!" << endl;
break;
}
}
} while (!flag);
break;
// Search a contact
case 4:
do
{
if (counter)
cout << "Try again" << endl;
counter++;
cout << "Search a name: \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
for (i = 0; i < 100; i++)
if (person[i].Search(temp_fName))
{
flag = 1;
break;
}
if (!flag)
cout << "Contact namew not found!" << endl;
} while (!flag);
break;
// Show all the contacts
case 5:
cout << "Showing Contacts" << endl;
printline('-', 25);
for (i = 0; i < 100; i++)
{
if (person[i].showAll())
{
flag = 1;
cout << "\n\n";
}
}
if (!flag)
cout << "No contacts found!" << endl;
break;
case 6:
// Write to file
cout << "Writing to file." << endl;
printline('-', 25);
for (int i = 0; i < 100; i++)
{
if (person[i].fName != "")
{
outfile << "Name: " << person[i].fName << " " << person[i].lName << "\n" << "Mobilenumber: " << person[i].mobileNo << "\n" << "Adress: " << person[i].adress << "\n" << "Email: " << person[i].epost << "\n" << "Birthday: " << person[i].birthday << "\n\n\n\n";
flag = 1;
cout << "\n\n";
}
}
break;
}
}while (1);
return 0;
}
//prints a line
void printline(char ch, int size)
{
for (int i = 0; i < size; i++)
cout << ch;
cout << "\n";
}
//Contact name validation
bool name_valid(string tname)
{
if (tname.size() > 20)
{
cout << "Invalid name!\nEnter a name within 20 characters!" << endl;
return 0;
}
else if (tname == "")
{
cout << "Invalid Name!\nName cannot be blank" << endl;
return 0;
}
else
return 1;
}
void writeToFile()
{
cout << "Writing to file." << endl;
printline('-', 25);
for (int i = 0; i < 100; i++)
{
if (person[i].fName != "")
{
outfile << "Name: " << person[i].fName << " " << person[i].lName << "\n" << "Mobilenumber: " << person[i].mobileNo << "\n" << "Adress: " << person[i].adress << "\n" << "Email: " << person[i].epost << "\n" << "Birthday: " << person[i].birthday << "\n\n\n\n";
flag = 1;
cout << "\n\n";
}
}
}
void readfromfile()
{
ifstream infile("Phonebook.txt");
string ignoreName, ignoreCell, ignoreAdress, ignoreEmail, ignoreBirthday;
string fileFirstname, fileLastname, fileCell, fileAdress, fileEmail, fileBirthday;
// Goes through the text file and put all the names in the contact class
while (!infile.eof())
{
getline(infile, ignoreName, ' ');
getline(infile, fileFirstname, ' ');
getline(infile, fileLastname);
getline(infile, ignoreCell, ' ');
getline(infile, fileCell);
getline(infile, ignoreAdress, ' ');
getline(infile, fileAdress);
getline(infile, ignoreEmail, ' ');
getline(infile, fileEmail);
getline(infile, ignoreBirthday, ' ');
getline(infile, fileBirthday);
// Check if the file is empty
if (!infile)
{
break;
}
for (int i = 0; i < 100; i++)
if (person[i].addContact(fileFirstname, fileLastname, fileAdress, fileEmail, fileCell, fileBirthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
}
infile.close();
}
Just pass in an array to the function (and others which are needed). Now the size of the array is known beforehand so we can protect it from array decay too. It'll look something like this,
void writeToFile(contact(&person)[100], std::fstream& outfile, bool& flag) { ... }
void readfromfile(contact(&person)[100], bool& flag) { ... }
Note that were passing in the others (flag and outfile) using the reference so that the actual variable can be altered.
From the two, I would recommend using the second option. Its clean, simple and safe (if you may).
Note: Try not to use using namespace std;. It not a good practice and basically your taking the std namespace and putting it in the global namespace. Now that namespace is huuuuggeeeeee. Later to access its objects and stuff, use :: operator.

C++ console crashes after running

guys, i have a problem.
After i run the program, the console just crashes.
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace: __pos (which is 4294967295) > this->size() (which is 9)
I mean, you will see.In the program there is an option "Add person", and when i add one, its all okay.But when i enter the program to add second person it crashes.Please, help!
The source code of the programs is:
#include <iostream>
#include <windows.h>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;
int main(){
system("chcp 1251 > nul");
system("title PeopleData");
string firstName;
string midName;
string lastName;
string fullName;
string line;
long ID = 27560000;
int age;
char gender;
cout << "1.Add person" << endl;
cout << "2.Read file" << endl;
cout << "3.Exit" << endl << endl;
cout << "Please, enter your choice: ";
int choice;
cin >> choice;
if(choice == 1)
{
system("cls");
ofstream myfile("Data.txt", ios::app);
ifstream file("Data.txt");
string IDLine;
int numberOfLines = 0;
if (myfile.is_open())
{
while (getline (file, line) )
{
numberOfLines ++;
}
file.close();
ifstream file("Data.txt");
int y = 0;
line = "";
while(getline(file, line))
{
IDLine = line;
if(y == numberOfLines - 5)
{
goto NextStep;
}
y++;
}
}
else
{
cout << "Unable to open file";
}
NextStep:
string LastID = IDLine;
if(LastID != "")
{
LastID.replace(LastID.find("ID: "), string("ID: ").length(), "");
ID = atoi(LastID.c_str()) + 1;
}
else
{
ID = 27560000;
}
cout << "First Name: ";
cin >> firstName;
cout << endl << endl;
cout << "Middle Name: ";
cin >> midName;
cout << endl << endl;
cout << "Last Name: ";
cin >> lastName;
cout << endl << endl;
cout << "Age: ";
cin >> age;
cout << endl << endl;
cout << "Gender (m / f): ";
cin >> gender;
fullName = firstName + " " + midName + " " + lastName;
myfile << "First Name: " << firstName << "\n";
myfile << "Middle Name: " << midName << "\n";
myfile << "Last Name: " << lastName << "\n";
myfile << "Full Name: " << fullName << "\n";
myfile << "Age: " << age << "\n";
myfile << "Gender: " << gender << "\n";
myfile << "ID: " << ID << "\n";
myfile << "\n---------------\n\n";
myfile.close();
file.close();
return 0;
}
if(choice == 2)
{
system("cls");
ifstream myfile ("Data.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else
{
setcolor(12);
cout << "Unable to open file";
}
}
if(choice == 3)
{
return 0;
}
system("pause > nul");
return 0;
}
`

Converting date format?

#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

Assigning Equipped Items to Player Characters in Text Adventure game?

I'm creating a text-based adventure game and Im a bit confused on how to actually assign a weapon object to a player. I'm inputting weapons from a text file called weapons.txt:
ID: 1.
Weapon Name: Katana.
Damage: 20.
Weight: 6.
ID: 2.
Weapon Name: Longsword.
Damage: 17.
Weight: 9.
ID: 3.
Weapon Name: WarAxe.
Damage: 22.
Weight: 20.
ID: 4.
Weapon Name: Staff.
Damage: 9.
Weight: 6.
And I have written a player and weapons class:
#include "Weapons.h"
#include <iostream>
#include <string>
using namespace std;
DoublyLinkedList<Weapons> weaponsList;
DoublyLinkedListIterator<Weapons> itr = weaponsList.getIterator();
Weapons :: Weapons() {
this->weaponID = 0;
this->weaponName = "";
this->damage = 0;
this->weight = 0;
}
Weapons :: Weapons(int weaponID,string weaponName,int damage,int weight) {
this->weaponID = weaponID;
this->weaponName = weaponName;
this->damage = damage;
this->weight = weight;
}
int Weapons :: getWeaponID() {
return weaponID;
}
string Weapons :: getWeaponName() {
return weaponName;
}
void Weapons::setWeaponName(string weaponName) {
this->weaponName = weaponName;
}
int Weapons :: getDamage() {
return damage;
}
int Weapons :: getWeight() {
return weight;
}
void Weapons :: getWeapons() {
string fileName = "Weapons\\Weapons.txt";
ifstream infile(fileName);
string garbage;
int id;
string weapon;
int damage;
int weight;
while(infile >> garbage >> id >> garbage >> garbage
>> garbage >> weapon >> garbage >> damage >> garbage
>> garbage >> weight >> garbage) {
cout << "ID: \t\t\t"<< id << "\n";
cout << "Weapon Name: \t\t"<< weapon << "\n";
cout << "Damage: \t\t" << damage <<"\n";
cout << "Weight: \t\t" << weight << "\n";
Weapons w1 (id,weapon,damage,weight);
weaponsList.Append(w1);
}
}
void Weapons :: printWeapons() {
int index = 0;
//Loop through the iterator.
for(itr.Start();itr.Valid();itr.Forth()) {
index++;
cout << "------------------Weapon------------------\n";
cout << "--------------------------------\n";
cout << "Position:\t\t" << index << "\n";
cout << "--------------------------------\n";
cout << "Weapon ID:\t\t" << itr.Item().getWeaponID() << "\n";
cout << "Weapon Name:\t\t" << itr.Item().getWeaponName() << "\n";
cout << "Damage:\t\t\t" << itr.Item().getDamage() << "\n";
cout << "Weight:\t\t\t" << itr.Item().getWeight() << "\n";
cout << "------------------------------------------\n";
}
cout << "Weapons: \t\t" << weaponsList.getCount() << "\n";
}
#include "Player.h"
#include "Validators.h"
#include <iostream>
Validators validators;
//--------------------------------------------------------------------------------------
// Name: Default Constructor.
//--------------------------------------------------------------------------------------
Player :: Player() {
this->firstName = "";
this->secondName = "";
this->level = 0;
this->experience = 0;
this->strength = 0;
this->weapons = weapons;
}
//--------------------------------------------------------------------------------------
// Name: Full Constructor.
//--------------------------------------------------------------------------------------
Player :: Player(string firstName,string secondName,int level,int experience,int strength,Weapons weapons) {
this->firstName = firstName;
this->secondName = secondName;
this->level = level;
this->experience = experience;
this->strength = strength;
this->weapons = weapons;
}
//--------------------------------------------------------------------------------------
// Name: Getters.
// Description: Makes you able to access the member variables of the player class.
//--------------------------------------------------------------------------------------
string Player :: getFirstName() {
return firstName;
}
void Player:: setFirstName(string firstName) {
this->firstName = firstName;
}
string Player :: getSecondName() {
return secondName;
}
int Player :: getLevel() {
return level;
}
int Player :: getExperience() {
return experience;
}
int Player :: getStrength() {
return strength;
}
void Player :: playerCreation() {
string inputFirstName = "Please enter your first name: ";
firstName = validators.getString(inputFirstName);
string inputSecondName = "Please enter your second name: ";
secondName = validators.getString(inputSecondName);
level = 0;
experience = 0;
strength = 8;
weapons.getWeaponName();
}
void Player::loadPlayer() {
//string fileName = "Players\\" + getFirstName()+ getSecondName() + ".txt";
string fileName = "Players\\ConorPendlebury.txt";
ifstream infile(fileName);
string garbage;
string loadFirstName;
string loadLastName;
int loadLevel;
int loadExperience;
int loadStrength;
Weapons weapons;
while(infile>>garbage,infile>>garbage,infile>>loadFirstName,infile>>garbage,
infile>>garbage,infile>>loadLastName,infile>>garbage,infile>>loadLevel,
infile>>garbage,infile>>loadExperience,infile>>garbage,infile>>loadStrength,infile>>garbage) {
cout << "First Name: \t"<< loadFirstName << "\n";
cout << "Second Name: \t"<< loadLastName << "\n";
cout << "Level: \t\t" << loadLevel <<"\n";
cout << "Experience: \t" << loadExperience << "\n";
cout << "Strength: \t" << loadStrength << "\n";
}
//this->setFirstName(firstName);
}
void Player::savePlayer() {
string fileName = "Players\\" + getFirstName()+ getSecondName() + ".txt";
cout << "File: \t\t" << fileName << " was saved" << endl;
ofstream oFile(fileName);
oFile << "First Name: " << this->getFirstName() << endl;
oFile << "Second Name: " << this->getSecondName() << endl;
oFile << "Level: " << this->getLevel()<< endl;
oFile << "Experience: " << this->getExperience()<< endl;
oFile << "Strength: " << this->getStrength()<< endl;
oFile << "Weapon: " << weapons.getWeaponName();
}
I am able to take the weapons from the file and add them to a Linkedlist but I'm stuck on how to assign certain weapons to the player before and after run-time.
Please can anybody help? Thanks.