I was wondering how I could have a program output one of two strings at random.
Hard to explain but this is my example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string age;
cout << "How old are you?" << endl;
cin >> age;
if (age < 0)
{
cout << "Invalid age" << endl;
}
if (0 >= age && age <<= 3)
{
cout << "Oh you're just a baby" << endl;
// OR (random)
cout << "Time to take a nap!" << endl;
}
return 0;
}
I want to program to output either, "Oh, you're just a baby" or "Time to take a nap!" at random whenever the user inputs a number between 0 and 3. Can anybody explain this?
try :
#include <cstdlib>
...
...
...
/* initialize random seed: */
srand(time(NULL));
/* generate secret number: */
int ss = rand() % 2;
if (ss) {
cout << "Oh you're just a baby" << endl;
} else {
cout << "Time to take a nap!" << endl;
}
You can also try this:
take input from user and compare it to random generated value and print output according to it:
#include <iostream>
using namespace std;
int main()
{
int age;
srand(time(NULL));
int a = rand()%3;
cout<<a<<endl; // print the random generated number (between 0 and 3 )
cout << "How old are you?" << endl;
cin >> age;
if (age < 0)
{
cout << "Invalid age" << endl;
}
if(age == a){
cout << "Oh you're just a baby" << endl;
}else{
cout << "Time to take a nap!" << endl;
}
return 0;
}
This uses the STL and only does the random selection from a table, without any user input:
#include <array>
#include <chrono>
#include <cstddef>
#include <iostream>
#include <random>
using std::cout;
using std::endl;
int main(void) {
// The size of the table:
constexpr size_t n = 2;
// A table of insults:
constexpr std::array<const char*, n> insults = {
"Oh, you're just a baby!",
"Time to take a nap."
};
// Boilerplate to initialize a RNG:
const std::default_random_engine::result_type seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
// Generate a random index into the string table:
std::uniform_int_distribution<size_t> distribution(0, n-1);
// A random number from distribution:
const size_t x = distribution(generator);
// Our random string:
const char* const s = insults[x];
cout << s << endl;
return EXIT_SUCCESS;
}
Related
I'm an absolute beginner in c++. Literally. It's just been a week.
Today I was writing a program to test how many iterations are needed to make a certain number palindromic.
Here is the code:
#include <iostream>
#include <string>
#include <algorithm>
/* This program calculates the steps needed
to make a certain number palindromic.
It is designed to output the values for
numbers 1 to 1000
*/
using namespace std;
class number
{
public:
string value;
void reverse();
};
void number::reverse()
{
std::reverse(value.begin(),value.end());
}
void palindrome(number num)
{
string n=num.value;
number reversenum, numsum, numsumreverse;
reversenum=num;
reversenum.reverse();
numsum.value=num.value;
numsumreverse.value=numsum.value;
numsumreverse.reverse();
int i=0;
while (numsum.value.compare(numsumreverse.value) !=0)
{
reversenum=num;
reversenum.reverse();
numsum.value=to_string(stoll(num.value,0,10)+stoll(reversenum.value,0,10));
numsumreverse.value=numsum.value;
numsumreverse.reverse();
num.value=numsum.value;
i++;
}
cout << "The number " << n << " becomes palindromic after " << i << " steps : " << num.value << endl;
}
int main()
{
number temp;
int i;
for (i=1; i<1001; i++)
{
temp.value=to_string(i);
palindrome(temp);
}
return 0;
}
It goes on smooth for numbers upto 195. But, in case of 196 I get an error.
It says:
terminate called after throwing an instance of 'std::out_of_range'
what(): stoll
I cannot make out what to do. I tried starting from 196 but the error persisted. Any help will be greatly appreciated. :)
UPDATE: This time I tried to do it using ttmath library. But arghs! It again stops at 195 and doesn't even report an error! I might be doing something foolish. Any comments would be appreciated. Here's the updated code:
#include <iostream>
#include <string>
#include <algorithm>
#include <ttmath/ttmath.h>
/* This program calculates the steps needed
to make a certain number palindromic.
It is designed to output the values for
numbers 1 to 1000
*/
using namespace std;
class number
{
public:
string value;
void reverse();
};
void number::reverse()
{
std::reverse(value.begin(),value.end());
}
template <typename NumTy>
string String(const NumTy& Num)
{
stringstream StrStream;
StrStream << Num;
return (StrStream.str());
}
void palindrome(number num)
{
string n=num.value;
number reversenum, numsum, numsumreverse;
reversenum=num;
reversenum.reverse();
numsum.value=num.value;
numsumreverse.value=numsum.value;
numsumreverse.reverse();
ttmath::UInt<100> tempsum, numint, reversenumint;
int i=0;
while (numsum.value.compare(numsumreverse.value) !=0)
{
reversenum=num;
reversenum.reverse();
numint=num.value;
reversenumint=reversenum.value;
tempsum=numint+reversenumint;
numsum.value=String<ttmath::UInt<100> >(tempsum);
numsumreverse.value=numsum.value;
numsumreverse.reverse();
num.value=numsum.value;
i++;
}
cout << "The number " << n << " becomes palindromic after " << i << " steps : " << num.value << endl;
}
int main()
{
number temp;
int i;
for (i=196; i<1001; i++)
{
temp.value=to_string(i);
palindrome(temp);
}
return 0;
}
UPDATE: It's solved. Some research suggested that 196 might be a Lychrel Number. And the result I was getting after implying the ttmath library is just reassuring that my algorithm works. I have tried it out for all the numbers upto 10000 and it gave out the perfect results. Here is the final code:
#include <iostream>
#include <string>
#include <algorithm>
#include <ttmath/ttmath.h>
#include <limits>
/* This program calculates the steps needed
to make a certain number palindromic.
It is designed to output the values for
numbers inside a desired range
*/
using namespace std;
string LychrelList;
int LychrelCount=0;
class number
{
public:
string value;
void reverse();
};
void number::reverse()
{
std::reverse(value.begin(),value.end());
}
template <typename NumTy>
string String(const NumTy& Num)
{
stringstream StrStream;
StrStream << Num;
return (StrStream.str());
}
void palindrome(number num)
{
string n=num.value;
number reversenum, numsum, numsumreverse;
reversenum=num;
reversenum.reverse();
numsum.value=num.value;
numsumreverse.value=numsum.value;
numsumreverse.reverse();
ttmath::UInt<100> tempsum, numint, reversenumint;
int i=0;
while ((numsum.value.compare(numsumreverse.value) !=0) && i<200)
{
reversenum=num;
reversenum.reverse();
numint=num.value;
reversenumint=reversenum.value;
tempsum=numint+reversenumint;
numsum.value=String<ttmath::UInt<100> >(tempsum);
numsumreverse.value=numsum.value;
numsumreverse.reverse();
num.value=numsum.value;
i++;
}
if (i<200) cout << "The number " << n << " becomes palindromic after " << i << " steps : " << num.value << endl;
else
{
cout << "A solution for " << n << " could not be found!!!" << endl;
LychrelList=LychrelList+n+" ";
LychrelCount++;
}
}
int main()
{
cout << "From where to start?" << endl << ">";
int lbd,ubd;
cin >> lbd;
cout << endl << "And where to stop?" << endl <<">";
cin >> ubd;
cout << endl;
number temp;
int i;
for (i=lbd; i<=ubd; i++)
{
temp.value=to_string(i);
palindrome(temp);
}
if (LychrelList.compare("") !=0) cout << "The possible Lychrel numbers found in the range are:" << endl << LychrelList << endl << "Total - " << LychrelCount;
cout << endl << endl << "Press ENTER to end the program...";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin,s);
cout << "Thanks for using!";
return 0;
}
It's a really awesome community. Special thanks to Marco A. :)
UPDATE AGAIN: I've devised my own add() function that cuts the program's dependency on external libraries. It resulted in a smaller executable and faster performance too. Here is the code:
#include <iostream>
#include <string>
#include <algorithm>
#include <limits>
/* This program calculates the steps needed
to make a certain number palindromic.
It is designed to output the values for
numbers inside a desired range
*/
using namespace std;
string LychrelList;
int LychrelCount=0;
string add(string sA, string sB)
{
int iTemp=0;
string sAns;
int k=sA.length()-sB.length();
int i;
if (k>0){for (i=0;i<k;i++) {sB="0"+sB;}}
if (k<0) {for (i=0;i<-k;i++) {sA="0"+sA;}}
for (i=sA.length()-1;i>=0;i--)
{
iTemp+=sA[i]+sB[i]-96;
if (iTemp>9)
{
sAns=to_string(iTemp%10)+sAns;
iTemp/=10;
}
else
{
sAns=to_string(iTemp)+sAns;
iTemp=0;
}
}
if (iTemp>0) {sAns=to_string(iTemp)+sAns;}
return sAns;
}
void palindrome(string num)
{
string n=num;
string reversenum, numsum, numsumreverse;
numsum=num;
numsumreverse=numsum;
reverse(numsumreverse.begin(),numsumreverse.end());
int i=0;
while ((numsum.compare(numsumreverse) !=0) && i<200)
{
reversenum=num;
reverse(reversenum.begin(),reversenum.end());
numsum=add(num,reversenum);
numsumreverse=numsum;
reverse(numsumreverse.begin(),numsumreverse.end());
num=numsum;
i++;
}
if (i<200) cout << "The number " << n << " becomes palindromic after " << i << " steps : " << num << endl;
else
{
cout << "A solution for " << n << " could not be found!!!" << endl;
LychrelList=LychrelList+n+" ";
LychrelCount++;
}
}
int main()
{
cout << "From where to start?" << endl << ">";
int lbd,ubd;
cin >> lbd;
cout << endl << "And where to stop?" << endl <<">";
cin >> ubd;
cout << endl;
string temp;
int i;
for (i=lbd; i<=ubd; i++)
{
temp=to_string(i);
palindrome(temp);
}
if (LychrelList.compare("") !=0) cout << "The possible Lychrel numbers found in the range are:" << endl << LychrelList << endl << "Total - " << LychrelCount;
cout << endl << endl << "Press ENTER to end the program...";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin,s);
cout <<endl << "Thanks for using!";
return 0;
}
You guys here have helped me a lot to find my own way. Thanks everyone. :)
You're overflowing long long since the last two valid values of num.value and reversenum.value are 7197630720180367016 and 6107630810270367917 which, added together, are way above the maximum size of a long long (9223372036854775807 on my machine). That will yield a negative value and spoil your next call to stoll
std::out_of_range is thrown if the converted value would fall out of the range of the result type or if the underlying function (std::strtol or std::strtoll) sets errno to ERANGE.
(reference)
If you're trying to get the next smallest palindrome, you should use another approach like the one I explained here.
You can find a Live Example here
If you prefer to/must continue with your approach you should either do the addition manually on the strings or use a bigint library (again take a look at here and modify the plusOne() function to your liking)
From http://www.cplusplus.com/reference/string/stoll/
If the value read is out of the range of representable values by a long long, an out_of_range exception is thrown.
The ll data type cant handle the string length. My debugger tells me 196 breaks on the value
std::stoll (__str=\"9605805010994805921-\", __idx=0x0, __base=10)
The long long is too small.
You might want to do the addition on the strings themselves, without resorting to a numeric type.
When I try to run this code on Microsoft Visual Studio C++; It runs but the value of cost that is being outputted is wrong. Why is that? I do realize that I am not including a default statement, and that I am declaring cost twice, this is because I get the debug error that cost has no declared value, so what I assume is going on is the switch statement is not processing because it some how is not understanding the
cout << "Pizza";
How do I fix this?
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include <Windows.h>
#include <string>
using namespace std;
int main()
{
int a, b, c, d, e, f, m, p, k, User_Input, Pizza , cost;
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
k = 0;
cost = 0;
cout << "What is your favorite vegetarian food from the list below?" << endl;
Sleep(1500);
cout << "Pizza\n";
Sleep(200);
cout << "IceCream\n";
cin >> User_Input;
switch (User_Input)
{
case 1:
cout << "Pizza";
cost = 5;
break;
case 2:
cout << "IceCream";
cost = 5;
break;
}
Sleep(2000);
cout << "The total cost will be: " << cost;
cout << "\n\n\n\t\t\t";
return 0;
}
User_Input is of type "int", you are going to get unexpected results if you try to read a string via cin to that variable. What you probably want to do is either:
read into a string and do a string comparison
read into a string, convert to an int, and do the switch statement
A simplified example:
#include <iostream>
#include <string>
int main()
{
std::string user_input;
int cost = 0;
std::cout << "What is your favorite vegetarian food from the list below?\nPizza\nIceCream\n";
std::cin >> user_input;
if(user_input == "Pizza") {
cost = 5;
} else if (user_input == "IceCream") {
cost = 10;
}
std::cout << "The total cost will be: " << cost << std::endl;
return 0;
}
I'm writing a basic random number guessing game, and I'm trying to perfect it a bit when it comes to entering illegal characters, and as long as numbers outside of the range 1-100 are entered the program tells the user and the user gets to redo it, same goes with letters. However, if you enter 23x5 you end up getting double error messages, you get both the letter and a too high/too low depending on the random number. How do I sort it out so that this entry would go under the letter error message as well?
Here's my code:
Header.h
#ifndef HEADER_H
#define HEADER_H
int nGuessedNumber;
int nNumberOfGuesses = 1;
int nRandomNumber;
int UserInput();
#endif
Source.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
extern int nGuessedNumber;
int UserInput()
{
while(!(cin >> nGuessedNumber))
{
cin.clear();
while(cin.get() != '\n'){}
cout << "I asked for a number between 1 and 100.\n";
}
return nGuessedNumber;
}
main.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Header.h"
using namespace std;
int main()
{
srand(time(0));
nRandomNumber = rand() % 100 + 1;// sets random number between 1 and 100
cout << "Guess a number from 1 too 100: " << endl;
UserInput();
while (nGuessedNumber != nRandomNumber)
{
if ((nGuessedNumber < 1) || (nGuessedNumber > 100))
{
cout << "Oi! Between 1 and 100!\n";
UserInput();
}
else
{
if (nGuessedNumber < nRandomNumber)
{
for (nGuessedNumber; nGuessedNumber < nRandomNumber; nNumberOfGuesses++)
{
cout << "Too low, try again!" <<endl;
UserInput();
}
}
else if (nGuessedNumber > nRandomNumber)
{
for (nGuessedNumber; nGuessedNumber > nRandomNumber; nNumberOfGuesses++)
{
cout << "Too high, try again!"<< endl;
UserInput();
}
}
}
}
if (nGuessedNumber == nRandomNumber)
{
cout << "Congratulations! " << nGuessedNumber << " is correct!" << endl;
cout << "You guessed " << nNumberOfGuesses << " times." << endl;
}
system("PAUSE");
return 0;
}
Read whole lines from std::cin and parse them individually using std::istringstream:
int UserInput()
{
std::string line;
while (getline(std::cin, line)) {
std::istringstream is(line);
if (is >> nGuessedNumber) {
...
return nGuessedNumber;
} else {
...
}
}
}
I'm needing help in adding commas to the number the user enters, some guidance or help would be appreciated. So far I have it where i store the first three digits and the last six digits and then simply format it.
#include<iostream>
using namespace std;
int main ( int argc, char * argv[] )
{
unsigned long long userInput;
int fthreeDigit;
cout << "Enter a long long number: " << endl;
cin >> userInput;
fthreeDigit = ( userInput / 1000 );
userInput %= 1000;
cout << "Your Number: " << fthreeDigit << "," << userInput << endl;
system("pause");
return 0;
}
Is this what you need? The locale will do this for you correctly.
#include <iostream>
using namespace std;
int main ( int argc, char * argv[] )
{
unsigned long long userInput;
int fthreeDigit;
cout << "Enter a long long number: " << endl;
cin >> userInput;
std::cout.imbue(std::locale(""));
std::cout << userInput << std::endl;
return 0;
}
EDIT:
I have two solutions. first without playing with numbers (recommended) and second (division).
first solution is:
#include <cstdlib>
#include <iostream>
#include <locale>
#include <string>
using namespace std;
struct my_facet : public std::numpunct<char>{
explicit my_facet(size_t refs = 0) : std::numpunct<char>(refs) {}
virtual char do_thousands_sep() const { return ','; }
virtual std::string do_grouping() const { return "\003"; }
};
/*
*
*/
int main(int argc, char** argv) {
cout<<"before. number 5000000: "<<5000000<<endl;
std::locale global;
std::locale withgroupings(global, new my_facet);
std::locale was = std::cout.imbue(withgroupings);
cout<<"after. number 5000000: "<<5000000<<endl;
std::cout.imbue(was);
cout<<"and again as before. number 5000000: "<<5000000<<endl;
return 0;
}
before. number 5000000: 5000000
after. number 5000000: 5,000,000
and again as before. number 5000000: 5000000
RUN SUCCESSFUL (total time: 54ms)
and second (not recommended) is :
double f = 23.43;
std::string f_str = std::to_string(f);
or this
int a = 1;
stringstream ss;
ss << a;
string str = ss.str();
Then you can use string::substr() string::find() string::find_first_of() and similar methods to modify and format your string.
a similar topic
If you really want (have to) divide: (I think my version is cleaner & more efficient than the others)
unsigned long long userInput;
std::stringstream ss,s0;
std::string nr;
std::cout << "Enter a long long number: " << std::endl;
std::cin >> userInput;
int input=userInput;
int digits;
while(input>999){
input=input/1000;
digits=userInput-input*1000;
int mdigits=digits;
while(mdigits<100){s0<<"0";mdigits*=10;}
std::string s=ss.str();
ss.str("");
ss<<","<<s0.str()<<digits<<s;
userInput=input;
s0.str("");
}
std::string sf=ss.str();
ss.str("");
ss<<input<<sf;
std::cout << "Your Number: " << userInput << ";" << digits <<";"<<ss.str()<<std::endl;
Enter a long long number: 12345678 Your Number: 12;345;12,345,678
Here is the brute force but may be easiest to understand way to get every thousand digits with the help of a vector.
#include<iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ( int argc, char * argv[] )
{
long long userInput;
int fthreeDigit;
cout << "Enter a long long number: " << endl;
cin >> userInput;
vector <int> res; //use vector to store every 3 digits
while (userInput !=0)
{
fthreeDigit = userInput %1000;
res.push_back(fthreeDigit);
userInput = userInput / 1000 ;
}
std::reverse(res.begin(), res.end());
for (size_t i = 0; i < res.size()-1; ++i)
{
if (res[i] ==0)
{
cout << "000"<<",";
}
else
{
cout << res[i] << ",";
}
}
if (res[res.size()-1] == 0)
{
cout << "000";
}
else{
cout << res[res.size()-1];
}
cout <<endl;
cin.get();
return 0;
}
I tested this code with the following case:
Input: 123456 Output: 123,456
Input: 12 Output: 12
Input: 12345 Output: 12,345
Input: 1234567 Output: 1,234,567
Input: 123456789 Output: 123,456,789
Input: 12345678 Output: 12,345,678
I guess this is what you want according to your response to comments.
You could do this:
#include <iostream>
#include <string>
using namespace std;
string commify(unsigned long long n)
{
string s;
int cnt = 0;
do
{
s.insert(0, 1, char('0' + n % 10));
n /= 10;
if (++cnt == 3 && n)
{
s.insert(0, 1, ',');
cnt = 0;
}
} while (n);
return s;
}
int main()
{
cout << commify(0) << endl;
cout << commify(1) << endl;
cout << commify(999) << endl;
cout << commify(1000) << endl;
cout << commify(1000000) << endl;
cout << commify(1234567890ULL) << endl;
return 0;
}
Output (ideone):
0
1
999
1,000
1,000,000
1,234,567,890
// Accepts a long number, returns a comma formatted string
CString num_with_commas(long lnumber)
{
CString num;
num.Format(%d",lnumber);
if(num.GetLength() > 3) {num.Insert(num.GetLength()-3, ',');}
if(num.GetLength() > 7) { num.Insert(num.GetLength()-7, ','); }
if (num.GetLength() > 12) { num.Insert(num.GetLength()-12, ','); }
return(num);
}
Here is my code...What would be the best way to sort names alphabetically?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int StudentNum;
cout << "How many student are in the class?\n";
cin >> StudentNum;
string sname[25];
if (StudentNum < 1 || StudentNum > 25)
{
cout << "Please enter a number between 1-25 and try again\n";
return 0;
}
for (int i = 1; i <= StudentNum; i++)
{
cout << "Please enter the name of student #" << i << endl;
cin >> sname[i];
}
for (int output = 0; output <=StudentNum; output++)
{
cout << sname[output] << endl;
}
system ("pause");
return 0;
}
The standard way is to use std::sort:
#include <algorithm>
// ...
std::sort(sname, sname + StudentNum);
std::sort uses operator< by default, which actually does an alphabetical comparison for strings.
EDIT: Indeed, it should be StudentNum instead of 25.