How can I print out the time initialized by user input? - c++

Im new to coding in general and particularly to C++. Im trying to make something like google assistant, but text based, and am currently working on printing out the time when the user types in something like "timepls". I am using an arraybased kind of library for the code, so that I store preconfigured strings inside an array and compare the user input variable to each object in each array. and if the string matches with one of the arrays in the function, it gets executed. My problem is, that I have tried ctime and used the same initialisation code as with another function which I know works (its the only other function lol). Can someone help me to print out the current time with user input?
Heres my code:
#include <iostream>
#include <ctime>
using namespace std;
void howareyouq();
void whattimeisit();
int main(){
howareyouq();
whattimeisit();
}
void howareyouq(){
string howruq[4] = {"how are you?", "hru?", "how r u?", "hru"}; //array for the valid thingies
string user_input; //creating userinput variable
cin >> user_input; //writing user input to user_input
for (int i=0; i!=4; i++) {
if (user_input == howruq[i]) { //if the array contains something equal to user_input, this gets executed
cout << "Thanks, Im fine!" << endl; //the answer
}
}
}
void whattimeisit()
{
string thetimepls[] = {"timepls", "what time is it?", "how late is it?", "whats the time?", "time?"};
string user_input;
cin >> user_input;
for (int i=0; i++;) {
if (user_input == thetimepls[i]) {
time_t now = time(0);
char *date = ctime(& now);
cout << "The local date and time : " << date << endl;
}
}
}

Getting the bounds right and reading in a single time:
#include <iostream>
#include <ctime>
using namespace std;
void howareyouq(string const& user_input);
void whattimeisit(string const& user_input);
int main()
{
string user_input; //creating userinput variable
cin >> user_input; //writing user input to user_input
howareyouq(user_input);
whattimeisit(user_input);
}
void howareyouq(string const& user_input)
{
string howruq[4] = {"how are you?", "hru?", "how r u?", "hru"}; //array for the valid thingies
for (int i=0; i!=4; i++)
{
if (user_input == howruq[i]) { //if the array contains something equal to user_input, this gets executed
cout << "Thanks, Im fine!" << endl; //the answer
}
}
}
void whattimeisit(string const& user_input)
{
string thetimepls[] = {"timepls", "what time is it?", "how late is it?", "whats the time?", "time?"};
for (int i=0; i!=5; i++) {
if (user_input == thetimepls[i]) {
time_t now = time(0);
char *date = ctime(& now);
cout << "The local date and time : " << date << endl;
}
}
}

Related

C++ Loop for String

I am struggling to create a loop for getting input from user. The input must push_back() each instance.
#include <iostream>
#include <array>
#include <cstring>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
int main()
{
vector <string> bookQ = { "what","book","is","that","you","are","reading" };
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
int x = 0;
for (x != '1') { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl; //
cin >> x; //
getline(cin, input); //
bookQ.push_back(input); //
} //
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
Your for loop is missing the declaration and (iteration) expression parts:
for (declaration-or-expression; declaration-or-expression; expression)
so it should have looked like this:
for (;x != '1';) {
which is generally written as
while (x != '1') {
That would cause problems though since it would not stop directly when the user entered 1.
You are also comparing an int with a char ('1'), so in order to exit the loop, the user would have had to enter 49 (the ASCII value for 1), not 1.
You are also mixing formatted input (cin >> x) with unformatted input (getline). I suggest that you stick to one only.
Example:
while(cout << "Enter 1 to stop\n", getline(cin, input) && input != "1") {
bookQ.push_back(input);
}
Assuming you meant that input is a string, then you've made a few mistakes with types. First of all, you've used wrong type for variable x, you used int which is integer type, and the type string is required. Secondly, when comparing x with '1' you used single quotes, which define the type of variable as char, not string. To make 1 a string you should use double quotes, like so "1". Besides that, you have used for(condition), which is incorrect syntax. You should use while(condition). Also, when your loop iterates, the x variable is the input book name, and input variable is always an empty string, so I would suggest replace input with x everywhere. The working code is below.
P.S. I am not sure whether you want "1" to be in the final vector, so I haven't changed that
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> bookQ = {"what", "book", "is", "that", "you", "are", "reading"};
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
string x;
while (x != "1") {
cout << "Enter 1 to stop" << endl;
cin >> x;
bookQ.push_back(x);
}
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
simply check if input is 1 everytime the user enters somthing, and when it does = 1, simply break loop.
string x;
while (true) { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl;
cin >> x;
if (x == "1"){
break;
}
getline(cin, x);
bookQ.push_back(x);
}
}
First, your for syntax is wrong. You want a while loop instead, or in this case a do..while loop would make more sense. Also, you are pushing the user's input into the vector before validating what the input actually is.
Second, x is an integer, but '1' is a character whose ASCII value is number 49. Your loop will never end, because != will always be true. Since you want the user to enter number 1 to stop the loop, you need to drop the quotes:
Third, what is the point of pre-populating bookQ? Just declare the bookQ without any initial data, and then cout the entire question as a normal string. This way, after the user is done entering input, the vector will contain only the user's input and nothing else.
Try something more like this:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
vector <string> bookQ;
string input;
cout << "what book is that you are reading" << endl;
do {
cout << "Enter a book, or 1 to stop" << endl;
getline(cin >> ws, input);
if (input == "1") break;
bookQ.push_back(input);
}
while (true);
for (size_t i = 0; i < bookQ.size(); ++i) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}

Whats a good way to get the program to end based on user input?

I did my "Hello World", I'm just getting started on my programming adventure with C++. Here is the first thing I've written, what are some ways to get it to end with user input? I'd like a yes or no option that would terminate the program. Also any feedback is welcome, thank you
#include <iostream>
using namespace std;
void Welcome();
void calculateNum();
void tryAgain();
int main() {
Welcome();
while (true) {
calculateNum();
tryAgain();
}
system("pause");
}
void calculateNum() {
float userNumber;
cin >> userNumber;
for (int i = 100; i >= 1; i--) {
float cNumber = i* userNumber;
cout << i << " >>>>> " << cNumber << endl;
}
}
void Welcome() {
cout << "Welcome \n Enter a number to see the first 100 multiples \n";
}
void tryAgain() {
cout << "Try again? Enter another number... ";
}
Here is one option:
Switch to do ... while loop, with the condition at the end.
Make your tryAgain() function return a boolean and put it in the while condition.
In tryAgain function read input from the user, and compare it to expected answers.
First, lets add a new header for string, it will make some things easier:
#include <string>
Second, lets rebuild the loop:
do {
calculateNum();
} while (tryAgain());
And finally, lets modify the function:
bool tryAgain() {
string answer;
cout << "Try again? (yes / no)\n";
cin >> answer;
if (answer == "yes") return true;
return false;
}
Now, there is a slightly shorter way to write that return, but it might be confusing for new learners:
return answer == "yes";
You don't need the if because == is an operator that returns bool type value.
You can change your calculateNum() in the following way:
Change the return value of your calculateNum() function into bool to indicate whether the program shall continue or stop
read the input into a std::string
check if the string is equal to your exit string like 'q' for quit
3.a in that case, your function returns false to indicate the caller that the program shall stop
3.b otherwise, create a stringstream with your string and read the content of the stream into your float variable and continue as you do like now
In your loop in your main function you break if calculateNum() returned false
Here is a simple solution:
#include <iostream>
// Here are two new Includes!
#include <sstream>
#include <string>
using namespace std;
void Welcome();
// Change return value of calculateNum()
bool calculateNum();
void tryAgain();
int main()
{
Welcome();
while (true)
{
if (!calculateNum())
break;
tryAgain();
}
system("pause");
}
bool calculateNum()
{
//Read input into string
string userInput;
cin >> userInput;
//Check for quit - string - here just simple q
if (userInput == "q")
return false;
//otherwise use a std::stringstream to read the string into a float as done before from cin.
float userNumber;
stringstream ss(userInput);
ss >> userNumber;
//and proces your numbers as before
for (int i = 100; i >= 1; i--)
{
float cNumber = i * userNumber;
cout << i << " >>>>> " << cNumber << endl;
}
return true;
}
void Welcome()
{
cout << "Welcome \n Enter a number to see the first 100 multiples \n";
}
void tryAgain()
{
cout << "Try again? Enter another number... ";
}
Having your users input in a string you can even do further checks like checking if the user entered a valid number, interpret localized numbers like . and , for decimal delimitters depending on your system settings and so on.

Sorting string array alphabetically in a 2D array (C++)

I have coded thus far and I am not sure how to sort using the 2-dimensional array. Basically, one function is for sorting an array of strings, another function is for swapping two strings. Any help would be appreciated. (Also I am not allowed to use c++ 11 :/)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void input_name(string&);
void sort_names(string&);
void repeat_pro(int&);
void sortArray(string, int);
int main() {
string b_list[100][2];
string name;
int choice;
int count=0;
cout << "Welcome to the Business Sorting Program!" << endl;
do{
input_name(name);
b_list[count][1] = name;
count++;
repeat_pro(choice);
cout<<"\n \n Your Businesses are:"<<endl;
for(int j=0; j<count; j++){
cout<<b_list[j][1]<<endl;
}
cout << "\n\n";
}while(choice == 0);
cout << "Thanks for using this program"<<endl;
return 0;
}
void input_name(string &name){
cout << "Enter in the name of the business: ";
getline(cin, name);
}
void sort_names(string &name){
}
void repeat_pro(int &choice){
cout << "Do you want to enter in more names: ";
string answ;
cin>>answ;
cin.ignore(1000,'\n');
if (answ == "YES" || answ == "Y" || answ == "yes" || answ == "y"){
choice = 0;
}
else {
choice = 1;
}
}
it is not clear to me from the description what problem the program really tried to solve. I'm assuming it's kind of like a two column spreadsheet, the second column is the name entered by the user(but what is in the first column?).
assume you need to keep the array in sorted order as the data goes in, just do a binary search (you can do a linear search for small dataset like 100 entries).
// we don't have lambda before C++11
struct comparator {
bool operator () (const string (&x)[2], const string (&y)[2]) const {
return x[1] < y[1];
}
};
//... omitted
string data[100][2];
int count = 0;
while (count < 100) {
// no rvalue, move, rvo, etc. before C++11
string name;
input_name(name);
// no type deduction and lambda
string (*position)[2] =
std::lower_bound(&data[0], &data[count], name, comparator());
int index = position - &data[0];
// simulate an vector::insert operation, but for our array
for (int i = count; i > index; --i) {
// before we had move in C++, we would do swap with an empty element.
// in this case, the entry at data[count] is default constructed
std::swap(data[i][1], data[i-1][1]);
}
data[index][1] = name;
}
//... omitted
of course we can use a typedef to make it cleaner, but that's left to you.

EXC_BAD_ACCESS error with arrays in C++

sorry if this is a stupid question but I'm trying to write a program that compares 7 numbers that a user inputs to 7 numbers that the computer generates(a kind of lottery simulator). However, when i try to input the 7 numbers that the user inputs the program crashes after the second input. Please help, and thanks in advance!
This is the beginning of my main:
#include <iostream>
#include <iomanip>
#include "Implementation.hpp"
using namespace std;
int main()
{
string name;
cout << "What is your name?\n";
getline(cin, name);
while(1 != 0) //I know this will never be true, I'm just doing it
//because the return statement will
{ //end the program anyways if the user inputs 2
int *userNums = new int[7];
int *winningNums = new int[7];
int cont;
int matches;
cout << "LITTLETON CITY LOTTO MODEL\n";
cout << "--------------------------\n";
cout << "1) Play Lotto\n";
cout << "2) Quit Program\n";
cin >> cont;
if(cont == 2)
return 0;
getLottoPicks(&userNums);
And this is the getLottoPicks function:
void getLottoPicks(int *picks[])
{
int numsAdded = 0, choice;
while(numsAdded <= 7)
{
cout << "Please input a valid number as your lotto decision.\n";
cin >> choice;
if(noDuplicates(*picks, choice) == false)
continue;
*picks[numsAdded] = choice;
numsAdded++;
}
}
I'm fairly certain that it is a problem with the pointers that i'm trying to use, but without them I can't actually change the arrays I don't think, and I couldn't get the function to return an array.
If you're using C++, then you're probably better using a std::vector<int>, and passing in the reference to the vector in getLottoPicks.
However, your code should only be passing the int * to the getLottoPicks, and should process < 7 items - it's the classic off-by one.
call to getLottoPicks:
getLottoPicks(userNums);
and the new getLottoPicks code:
void getLottoPicks(int *picks)
{
int numsAdded = 0, choice;
while(numsAdded < 7)
{
cout << "Please input a valid number as your lotto decision.\n";
cin >> choice;
if(noDuplicates(picks, choice) == false)
continue;
picks[numsAdded] = choice;
numsAdded++;
}
}

Figuring out why Word Counter program output is 0 or 1

I need to figure out a bug with my program. When I type Hello World I am, it should count the number of spaces, but I keep getting 0 or 1. Below is my full program:
#include "windows.h"
#include <iostream>
#include <cctype>
using namespace std;
//Global declarations.
//Function prototypes.
void pause();
void numWords(string&);
int numWords(char []);
int main()
{
string userVal;
numWords(userVal);
char *conStr= new char[userVal.length()];
strcpy(conStr, userVal.c_str()); //String converted to a C-string.
int fin= numWords(conStr);
cout<< "The number of words in the sentence is "<< fin<< "."<< endl;
delete[] conStr;
conStr= 0;
pause();
return 0;
}
/***************************************FUNCTIONS**********************************************************************/
/*1st function to pause the program.*/
void pause()
{
cin.sync();
cin.ignore();
}
/*2nd function to ask the user for input. OP*/
void numWords(string &len)
{
cout << "Please enter a sentence and I will tell you how many words it has: " << endl;
cin >> len;
}
/*3rd function to count the number of total spaces in the sentence.*/
int numWords(char usStr[])
{
int wrdCount= 0,
chrCount= 0,
index= 0;
while(usStr[index]!= '\0')
{
if(isspace(usStr[index]))
{
if(chrCount)
{
wrdCount++;
chrCount= 0;
}
}
else
chrCount++;
index++;
}
if(chrCount)
wrdCount++;
return wrdCount;
}
Can anyone please explain why it doesn't count the spaces, or if I need another loop mechanism to make this work? Thank you.
CoryKramer's suggestion was correct. cin will stop after the first whitespace. If you want to read a whole line, you use getline. I've made changes to your code to show this as well as renamed the function you use to get the sentence from the user. Also, you don't have to convert to a c-style string for this to work, a string works just fine.
//Function prototypes.
void pause();
void getSentence(string&);
int numWords(string&);
int main()
{
string userVal;
getSentence(userVal);
int fin = numWords(userVal);
cout << "The number of words in the sentence is " << fin << "." << endl;
pause();
return 0;
}
void getSentence(string &len)
{
cout << "Please enter a sentence and I will tell you how many words it has: " << endl;
getline(cin, len);
}
int numWords(string& usStr)
{
int wrdCount = 0,
chrCount = 0,
index = 0;
while(index < usStr.length())
{
...
}
if(chrCount)
wrdCount++;
return wrdCount;
}
You also probably want to #include <string>