all!
I'm trying to find the best way to accept user input, timestamp it, then place it into a file with correct formatting (One timestamp/input per line. What is the best way to timestamp then give over to put it all in a file? Thanks!
Heres my barebones code as an example:
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;
//void passwordCheck()
//{
//
//}
string timestamp(string passwordInput1, string passwordInput2, string passwordInput3, string passwordInput4, string passwordInput5, string passwordInput6, string passwordInput7, string passwordInput8, string passwordInput9, string passwordInput10)
{
time_t now = time(0);
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
tm *gmtm = gmtime_s(&now);
dt = asctime(gmtm);
}
//void saveToFile()
//{
//
//cout << "I've saved 10 passwords for you." << endl;
//}
int main()
{
ofstream outputToFile;
outputToFile.open("manageMyPasswords.txt");
// Look for easier/cleaner way to do this.
string passwordInput1, passwordInput2, passwordInput3, passwordInput4, passwordInput5, passwordInput6, passwordInput7, passwordInput8, passwordInput9, passwordInput10;
// Put into a function then call back here.
cout << "Welcome to Password Manager!" << endl;
cout << " Enter your first password" << endl;
getline (cin, passwordInput1);
cout << "Enter the next password." << endl;
getline (cin, passwordInput2);
cout << "Enter the next password." << endl;
getline (cin, passwordInput3);
cout << "Enter the next password." << endl;
getline (cin, passwordInput4);
cout << "Enter the next password." << endl;
getline (cin, passwordInput5);
cout << "Enter the next password." << endl;
getline (cin, passwordInput7);
cout << "Enter the next password." << endl;
getline (cin, passwordInput8);
cout << "Enter the next password." << endl;
getline (cin, passwordInput9);
cout << "Enter the next password." << endl;
getline (cin, passwordInput10);
//void saveToFile();
system("pause");
return 0;
}
As I understood your question you need sth like this:
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <map>
int main(int argc, char** argv)
{
typedef std::multimap<time_t, std::string> Passwords;
Passwords passwords;
short counter = 1;
std::cout << "Enter passwords or \"quit\" to stop" << std::endl;
for (std::string line;;)
{
std::cout << "Enter password " << counter << " -> ";
getline(std::cin, line);
if (line.empty())
{
continue;
}
else if (line.compare("quit") == 0)
{
break;
}
passwords.insert(std::pair<time_t, std::string>(time(0), line));
counter++;
}
std::ofstream outputFile;
outputFile.open("manageMyPasswords.txt", std::ios::trunc);
for (Passwords::const_iterator it = passwords.begin(); it != passwords.end(); it++)
{
outputFile << it->first << " " << it->second << "\n";
}
outputFile.close();
return 0;
}
It will wait for users input infinitely, until "quit" is not entered. After that it will dump timestamps with password line by line.
P.S. I've used multimap, because you can have duplicate timestamps.
Update
It seems from your code that you need human-readable time. Use this function to retrieve current date and time:
// Returns current date-time formatted like [YYYY-MM-DD][HH:mm:ss]
const std::string GetCurrentDateTime()
{
time_t currentTime = time(0);
struct tm localDateTime;
char buf[80];
localtime_s(&localDateTime, ¤tTime);
strftime(buf, sizeof(buf), "[%Y-%m-%d][%X]", &localDateTime);
return buf;
}
Related
I'm trying to write a code for signup / login while being able to write and read from the file. So far I am able to write in the file and asked for the users input and displayed in the file (signup).
My problem is now,
How do I do the login part, in which when the user chooses login, they are able to choose what username they want based on a selection of usernames and the input they have made while choosing the first option?
How can this information be read and displayed in the file?
Expected output for user login
Choose you username:
0:mike
1:Linda
2:Martha
Expected input from the user
your choice: "Key in choice"
So far the code displayed works, but I am not sure what to do for my next step.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int option;
int age,height;
string name;
string database;
ofstream file_out;
ifstream file_in;
cout << " For sign up type 1" <<endl;
cout << " For log in type 2" <<endl;
cin >> option;
if ( option == 1 ) {
file_out.open("database.txt");
cout << "Input name: \n";
cin >> name;
cout << "Input age: \n";
cin >> age;
cout << " Input height: \n";
cin >> height;
//write file
file_out << name << endl;
file_out << age << endl;
file_out << height << endl;
file_out.close();
} else if (option == 2) {
//read file
file_in.open("database.txt");
cout << "choose your username: " << endl;
// input line of code
while ( getline(file_in, database));
//input line of code
cout << database << endl;
You can do something like this. Print all the usernames, but before printing out check if they are numbers with help of the stof function, if they are numbers we don't have to do anything, but if it is a string it will throw an exception, so in the catch block we print it and store it into dictionary/map for easy retrieval.
#include <fstream>
#include <iostream>
#include <map>
int main(void) {
std::fstream file;
file.open("secret.txt", std::ios::in);
std::map<int, std::string> map;
std::string username;
int count = 1;
while (!file.eof()) {
file >> username;
try {
std::stof(username);
} catch (...) {
std::cout << count << ". " << username << "\n";
map.insert(std::make_pair(count, username));
count++;
}
}
int choice;
std::cout << "Choose your username: ";
std::cin >> choice;
username = map.at(choice);
std::cout << "Your username is set to " << username;
return 0;
}
when i run the code, the output is my first and
last name and that's it.
I've used cin.clear, cin.sync and cin.ignore.
None of these seemed to work. However, when i used
cin.fail, why did this work?
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str_mystr;
cout << "What is your name? ";
getline (cin, str_mystr, '#');
cout << "Hello " << str_mystr << '\n';
// cin.ignore();
cout << "What is your favorite city? ";
getline (cin, str_mystr);
cout << "I like " << str_mystr << '\n';
return 0;
}
just do what you did for name
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str_mystr;
cout << "What is your name? ";
getline (cin, str_mystr, '#');
cout << "Hello " << str_mystr << '\n';
// cin.ignore();
cout << "What is your favorite city? ";
getline (cin, str_mystr,'#');
// ^^^^
cout << "I like " << str_mystr << '\n';
return 0;
}
adding '#' will do the work just fine
So here is the rundown:
I am creating a small music library using structs. The library has a few functions that it has to do with one of them being that I should be able to add new songs to the library. I have to use cin.get() and go from there but everytime I execute it, it goes into and infinite loop. Here is what my code for the add song functions looks like. The integer i is just some index value.
struct song {
char title[50];
char artist[50];
char minutes[50];
char seconds[50];
char album[50];
}info[50];
void new_song(int& i)
int main(){
}
new_song(i);
{
cin.get(info[i].title,50,'\n');
cin.ignore(100, '\n');
cin.get(info[i].artist, 50, '\n');
cin.ignore(50, '\n');
cin.get(info[i].minutes, 50, '\n');
cin.ignore(50, '\n');
cin.get(info[i].seconds, 50, '\n');
cin.ignore(50, '\n');
cin.get(info[i].album, 50, '\n');
cin.ignore();
}
Any help helps.
I'd probably do something like this instead of using cin.get(), C strings, and static arrays:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Song {
string title;
string artist;
string minutes;
string seconds;
string album;
};
void add_song_from_stdin(vector<Song> &songs) {
Song s;
getline(cin, s.title);
getline(cin, s.artist);
getline(cin, s.minutes);
getline(cin, s.seconds);
getline(cin, s.album);
songs.push_back(s);
}
int main() {
vector<Song> songs;
add_song_from_stdin(songs);
Song &song = songs[0];
cout << "song[0]:" << endl;
cout << " \"" << song.title << "\"" << endl;
cout << " \"" << song.artist << "\"" << endl;
cout << " \"" << song.minutes << "\"" << endl;
cout << " \"" << song.seconds << "\"" << endl;
cout << " \"" << song.album << "\"" << endl;
}
I have just started C++ after working with C for almost a year. I'm writing a program for a user to input info about a song. I read that I should use getline() to read strings with spaces. Here is my code:
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
typedef struct Song
{
char title[20];
char album[20];
char artist[20];
int year;
} song;
//store song info
Song Input;
char inputStr[20];
int inputYear;
cout << "Enter the name of a song: ";
getline(cin, inputStr);
strcpy(Input.title, inputStr);
cout << "Enter the album of your song: ";
getline(cin, inputStr);
strcpy(Input.album, inputStr);
cout << "Enter the artist of your song: ";
getline(cin, inputStr);
strcpy(Input.artist, inputStr);
cout << "Enter the year your song was released: ";
cin >> inputYear;
Input.year = inputYear;
//print
cout << "Song title: " << Input.title << endl;
cout << "From album: " << Input.album << endl;
cout << "Artist: " << Input.artist << endl;
cout << "Released: " << Input.year << endl;
return 0;
}
My compiler1 throws 3 errors, one for each of the getline() calls, not recognizing getline() despite the fact I have #include <string>. I have looked up sample usage of the getline() function.
Thanks for any help.
1I have wondered if this problem might concern an issue with the standard of C++ that my compiler supports. I did a bit of research and I did not find anything that helped me learn which standard I am using. Here's some info:
I'm using Terminal on Mac.
After g++ version:
Configured with: --prefix=/Applications/Xcode.app/Cont.../usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
These lines seem to be the only ones of use here, but I could give more info. If someone has any idea which standard of C++ this is, whether it's C++11, or C++14, or otherwise, that would also be very helpful. Thanks again.
UPDATE:
started from scratch, tried to take as much of your advice as possible while still sticking to some of what I know. No errors and works just as I hoped. Thanks for all your help.
New code:
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
struct Song
{
string title;
string artist;
string album;
string year;
}song;
int main()
{
Song Input;
cout << "Song? ";
getline(cin, Input.title);
cout << "Artist? ";
getline(cin, Input.artist);
cout << "Album? ";
getline(cin, Input.album);
cout << "Year? ";
getline(cin, Input.year);
cout << "Song: " << Input.title << endl;
cout << "Artist: " << Input.artist << endl;
cout << "Album: " << Input.album << endl;
cout << "Year: " << Input.year << endl;
return 0;
}
The version of getline you are using takes a std::string as a parameter, not an array of char. If you want to use an array of char (and you shouldn't), you need to use the member function version:
cin.getline( some_char_array, array_size );
I would switch from using char arrays to using string's everywhere. For example I would do your code like this:
#include <string>
#include <iostream>
struct Song{
std::string title;
std::string album;
std::string artist;
int year;
};
int main()
{
//store song info
Song Input;
int inputYear;
std::cout << "Enter the name of a song: ";
getline(std::cin, Input.title);
std::cout << "Enter the album of your song: ";
getline(std::cin, Input.album);
std::cout << "Enter the artist of your song: ";
getline(std::cin, Input.artist);
std::cout << "Enter the year your song was released: ";
std::cin >> Input.year;
//print
std::cout << "Song title: " << Input.title << '\n';
std::cout << "From album: " << Input.album << '\n';
std::cout << "Artist: " << Input.artist << '\n';
std::cout << "Released: " << Input.year << std::endl;
return 0;
}
My preference is to not use using namespace std; but there's nothing wrong with it. Notice that using strings directly I don't need to copy things. I can use getline to do all that for me. I also don't need to worry about overrunning the size of the char array because string does that for me as well.
When I enter this code and try to run it, it isn't working when the user selects option 1, to enter some text and a string to search for within their text. It outputs "enter text" and then "enter string to search" immediately after, without giving the user the chance to input some text. What is wrong?
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
char choice[1];
cout << endl;
cout << endl;
cout << "--MENU--" << endl;
cout << "1. Pattern Matching" << endl; // search for string within text
cout << "2. Sorting Techniques" << endl; // generate and then sort 10 random numbers
cout << "Enter your choice: " << endl;
cout << endl;
cin >> choice;
cout << endl;
if (choice[0] == '1') // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << "." << endl;
}
else
{
cout << "Did not find text." << endl;
}
}
This is because cin >> choice reads part of the current input line for the choice entered by the user. The first getline() call reads the remaining part of the input line immediately following the choice entered by the user. You need to ignore the rest of the input line after the choice.
cin >> choice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You will also need to add #include <limits> to the beginning of your code in order to pull in numerical_limits.
It looks as though you are defining some sort of char array for the user response. I would tend to make that a non-zero integer type with an exception if the choice is neither 1 nor 2. There are also some shortcuts for output formatting that reduces lines of code. Also, you would want to include the standard string class to accept the string. Maybe try something like the following:
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
int choice;
cout << "\n--MENU--\n"l;
cout << "1. Pattern Matching\n"; // search for string within text
cout << "2. Sorting Techniques\n"; // generate and then sort 10 random numbers
cout << "Enter your choice:\n";
cin >> choice+"\n";
if (choice == 1 && choice > 0 && choice != 0) // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << ".\n";
}
else
{
cout << "Did not find text.\n";
}
}}}