Why is srand() not being stored in my variable? - c++

This beginner's program I am trying to make is basically a program where a truly random number is generated and the "player" has to guess the number. The computer will respond "too high" or "too low" until the player guesses the right number.
I got this program idea from some website, and thought I should roll with it. This is my second program- my first being a simple I/O program.
Here is my code:
// BracketingSearch.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <istream>
#include <fstream>
using namespace std;
int main()
{
int x = srand(time(0));
cout << x << endl;
for (int x = 1; x <= 10; x++) {
cout << 1 + (rand() % 100) << endl;
}
string stall;
getline(cin, stall);
}
Side notes:
I don't think I need that many headers; I am still getting use to the c++ libraries.
Please critique my code as much as possible. I am eager to learn programming!
The string stall is just to make my console application pause for input, so I can see the results.
Thank you for everyone who can help!
-Mike

srand(time(0)) seeds the random number generated by rand(). Its return type is void. void type cant be stored in an integer type variable.
See here for more information on srand().

I rewrote the program to use the minimum of headers required. Since I think this is homework, I left the original error in place, but placed the error output from gcc here.
#include <iostream>
#include <cstdlib>
#include <ctime>
// this is a personal thing, but I avoid "using namespace std;"
// in any file, since it makes it less clear where some symbols
// came from
int main()
{
int x = std::srand(std::time(0)); // line 11
std::cout << x << std::endl;
for (int x = 1; x <= 10; x++) {
std::cout << 1 + (std::rand() % 100) << std::endl;
}
// Windows folklore -- you should better switch your ide to not close
// the terminal after the program was run
std::cin.get();
}
The output of g++ -Wall foo.cpp:
foo.cpp: In function 'int main()':
foo.cpp:11:40: error: void value not ignored as it ought to be
int x = std::srand(std::time(0));
^

Related

C++ duration_cast<>(time_point_end - tine_point_start). count() overflows

What I want to do, my project:
I want to make a program that waits 0.5 seconds, for example, does something, let's say cout << "Hello World", once and then again the same for about 10 times(this is a test for another program), but without sleep, sleep_for, sleep or anything similar BCS I don't want the processor to actually sleep, BCS at that time the processor does not just wait, it does nothing for that time, for these 0.5 seconds it does nothing and I don't want that, and the main reason is BCS it also doesn't take input.
What I tried:
What I tried was to keep two points in time(time_point start,end), duration_cast their difference (end - start) in a for loop ((int i = 0;i < 10;i++)), and if their difference was 500 milliseconds, then, cout << "Hello World\n";.
My code looked something like this:
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace chrono;
int main()
{
time_point<steady_clock> t = steady_clock::now():
for (int i = 0; i < 10;)
{
duration<double> d = steady_clock::now() - t;
uint32_t a = duration_cast<milliseconds>(d).count();
if (a >= 500)
{
cout << a << " Hello World!" << endl;
t = steady_clock::now();
i++;
}
}
return 0;
}
My problem:
It overflows, most of the time, I don't know what exactly overflows, but a appears to be sometimes 6??? others 47??? (? = some digit)
I tried many things, I ended up to something like this:
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace chrono;
int main()
{
time_point<high_resolution_clock> t = high_resolution_clock::now();
for (int i = 0; i< 10;)
{
duration<double,ratio<1,1000000>> d = high_resolution_clock::now() - t;
uint32_t a = duration_cast<microseconds>(d).count();
if (d >= microseconds(500000) )
{
cout << a << " Hello World!" << endl;
i++;
t = high_resolution_clock::now();
}
}
return 0;
}
It didn't really solve the problem, but the max value appears is `~1500(1500000 in microseconds) and when it happens it takes longer to print the message, I don't know if its still overflow, to be honest, but...
Question
Anyway, do you have any suggestions about how to stop the overflow or a completely different way to achieve what I want, even if you don't, thanks for spending time to read my question, I hope to express someone else's question if there someone who has the same question as me.
Not sure if this is what you're looking for or not. But if not, maybe we can build on this to figure out what you want:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
auto t = steady_clock::now();
for (int i = 0; i < 10; ++i)
{
auto t1 = t + 500ms;
while (steady_clock::now() < t1)
;
cout << duration<double>(t1-t).count() << " Hello World!" << endl;
t = t1;
}
}
The code sets a time_point for 500ms in the future, and then enters a busy loop until that future time_point is now.

C++: Passing vector to function and then calling function in main. Missing something

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
void getAnswer(std::vector<std::string> &answers, int nAnswers)
{
int index = rand() % nAnswers;
}
int main()
{
std::vector<string> answers;
answers.push_back("Most Certainly");
answers.push_back("Absolutely");
answers.push_back("Yes");
answers.push_back("You Can Bet On It");
answers.push_back("Odds look good");
answers.push_back("Let's talk about that some other time");
answers.push_back("Odds don't look so good");
answers.push_back("I think you know the answer to that question");
answers.push_back("I don't think I'm qualified to answer that question");
answers.push_back("Absolutely Not");
answers.push_back("I Don't Think So");
answers.push_back("Um...no");
std::vector<string> qAnswers(answers);
answers.size();
string questionAsked;
bool pgExit = false;
srand((unsigned int)time(NULL));
cout << "\nWelcome to the Magic 8Ball.\n";
cout << "\nAsk a question and I will predict the answer!\n" << endl;
//loop and ask the user to enter a question or enter "x" to stop
while (!pgExit) {
cout << "What is your question? (Type question or Enter 'x' to exit) " << endl;
//use getline to get the question
getline(cin, questionAsked);
//call getAnswer with your array and number of possible answers to get an answer
getAnswer(answers, answers.size());
//output the answer
if (questionAsked.compare("x") == 0)
{
cout << "Maybe next time. Have a good day.";
pgExit = true;
}
if (questionAsked.compare("") != 0 && questionAsked.compare("x") != 0)
{
getAnswer;
std::cout << getAnswer(answers, answers.size()) << std::endl;
}
}
}
The issue I am having is when I compile, it is saying 'no operator matches "<<" these operands. Standard operands are: std::ostream << void'
I am not sure I understand. I am passing the vector string and the vector size to void getAnswers to get the randomize for the answers. What am I missing?
Any help is greatly appreciated.
void getAnswer(std::vector<std::string> &answers, int nAnswers)
The void return "type" states explicitly that this function returns nothing so you cannot then go and attempt to use that return value in an expression:
std::cout << getAnswer(answers, answers.size()) << std::endl;
Assuming that you will eventually return a random answer from your list of answers (based on code to date), the first thing you should do is dummy up a reurn value:
std::string getAnswer(std::vector<std::string> &answers, int nAnswers)
{
// Just return last one for now (make sure you
// have at least one in the collection).
return answers[nAnswers - 1];
}
Then you can later adapt it to provide a random one. I could have just provided the complete function but, since this is probably educational work, you'll learn a lot more by doing this yourself (this answer is just to get you over your specific problem).
I have included some sample code at the bottom for you to look over (and for future readers who may not be doing the classwork) but I urge you to try yourself first.
As an aside, you should also be aware that you have some rather superfluous lines in your code, specifically:
answers.size();
getAnswer(answers, answers.size());
getAnswer;
None of these do anything useful, they simply evaluate the expression and throw away the result.
I'm also not why you attempt to create a second vector from the original, especially since you don't use it anywhere:
std::vector<string> qAnswers(answers);
As mentioned earlier, my sample code follows. Please do not use it verbatim if you value your marks (or integrity) - any educator worth their salt will be using plagiarism detection tools:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
// Anon namespace to hide this in translation unit.
namespace {
// No need to pass in size, vector has this.
const std::string &getAnswer(const std::vector<std::string>answers) {
return answers[std::rand() % answers.size()];
}
};
int main() {
srand(static_cast<unsigned int>(time(nullptr)));
// Can be const if initialised rather than each entry pushed.
const std::vector<std::string> answers = {
"Most Certainly", "Absolutely", "Yes", "You Can Bet On It",
"Odds look good", "Let's talk about that some other time",
"Odds don't look so good",
"I think you know the answer to that question",
"I don't think I'm qualified to answer that question",
"Absolutely Not", "I Don't Think So", "Um...no",
};
std::cout << "\nWelcome to the Magic 8Ball.\n";
std::cout << "\nAsk a question and I will predict the answer!\n";
// Infinite loop, use break to exit.
while (true) {
// Ask and get response.
std::cout << "\nWhat is your question (x to exit)? " << std::endl;
std::string questionAsked;
std::getline(std::cin, questionAsked);
// Exit loop if told so.
if (questionAsked == "x") {
std::cout << "Maybe next time. Have a good day.\n\n";
break;
}
// Answer any non-blank question.
if (! questionAsked.empty()) {
std::cout << getAnswer(answers) << '\n';
}
}
}

Error when trying to print a private static integer from class. C++

I am having a problem with my code. Everytime I try to print my private static int total from the DivSales class, the program runs however it prints "00007FF768191492" Can someone please tell me what I've done wrong in my code? I am using C++ in Visual Studios. Keep in note that also I tried to print out DivSales::totalSale; in the main function however I got a similar output(the program runs) that says "00007FF726FF1492". Thank you for helping me.
#include <iostream>
#include <string>
#include <iomanip>
#include <Windows.h>
using namespace std;
class DivSales
{
private:
static int total;
public:
int qArr[4]; // here is the declared array I input the 4 integers
static int totalSale()
{
return total; // here is the function to return total.
}
void fourSale(int first, int second, int third, int fourth) //these integers are inputted by user.
{
if (valid(first) == true) //this and below is an example of how I am adding to the total variable. Imagine 3 more of these.
{
qArr[0] = first;
total += first;
}
}
int DivSales::total = 0;
int main()
{
DivSales div1; //here i declare an object. I have 5 more but I will display two for example purposes.
div1.fourSale(6543, 3000, 4000, 5000); // here i input the 4 integers
cout << div1.totalSale << endl << endl; // here I try to print out the total however it prints the error I was talking about.
}
The code here:
cout << div1.totalSale << endl << endl;
Prints the address of the function.
To print the returning value of the function, you must first call it with parentheses.
cout << div1.totalSale() << endl << endl;

How come this program waits 10 seconds instead of counting down?

I was trying out some c++11 code, and I tried to write a program that counts down from 10, sleeping in between the outputs. Here's what I have so far:
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
void Sleep(int x)
{
std::this_thread::sleep_for(std::chrono::duration<int>(x));
}
int main()
{
for (int x=10; x>0; x--) {
cout << x << "...";
Sleep(1);
}
cout << " FIRE!!\n";
}
The problem is, this code waits 10 seconds and then prints all of the output, instead of counting down from 10. How come this is? And how can I fix it?
(By the way, I tried this on a computer running Linux Mint 17 and MacOSX 10.9, and both times I got the same result)
Probably because you don't flush the output. Try this
cout << x << "..." << flush;
Stream output can be buffered, which means the results don't always appear immediately. Flushing at least increases the chance that you will see some output immediately.
You need to flush the output each time round the loop, otherwise the runtime system will wait for the buffer to be full or (sometimes) an end of line to be sent.
Also, when using std::chrono::duration<> it is better to use one of the explicitly defined types if possible for readability. In this case you are measuring times in seconds so I used std::chrono::seconds in your example:
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
void Sleep(int x)
{
// better to use explicit types for duration
// for readability
std::this_thread::sleep_for(std::chrono::seconds(x));
}
int main()
{
for(int x = 10; x > 0; x--) {
cout << x << "..." << std::flush; // need to flush here
Sleep(1);
}
cout << " FIRE!!\n";
}

Output conflicts between C & C++

Greetings Everyone
I am currently trying to write a multi-language program (C, C++ and fortran) though am achieving segmentation errors. I've ruled out vectors and the like in: Accessing public class memory from C++ using C
I've narrowed now the cause to the use of 'cout' experssions in my C++ segments and printf(...) in C segments. Depending on which order I run these at I always get segmentation error when using the 2nd type, like so:
cout first, then printf(...) will crash at first C output function
printf(...), then cout will crash at first C++ output function
I am #include <iostream> in my C++ sources, and #include <stdio.h> & #include <stdlib.h> in my C sources.
Is there a library conflict that I am not aware of?
Requested code:
main.cpp
#include <iostream>
#include <vector>
#include "CFE.h"
ios::sync_with_stdio(true);
using namespace std;
vector<float> DensityArray;
vector<float> EnergyArray;
int main()
{
int X = ReturnX ();
int Y = ReturnY ();
cout << "X " << X << endl;
cout << "Y " << Y << endl;
EnergyArray.resize(Y*X);
DensityArray.resize(Y*X);
CFE(&DensityArray[0], &EnergyArray[0]);
cout << "X " << X << endl; //causes Segmentation break
cout << "Y " << Y << endl; //causes Segmentation break
system ("PAUSE");
return 0;
}
CFE.h
#ifdef __cplusplus
extern "C" {
#endif
int ReturnX ();
int ReturnY ();
void CFE(float density[], float energy[]);
#ifdef __cplusplus
}
#endif
CFE.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "BCs.h"
#include "EMatrix.h"
#include "Numbering.h"
#include "KMatrix.h"
#include "fg_types.h"
#include "Solve.h"
int ReturnX ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
fclose(infile);
return elemX;
}
int ReturnY ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
fclose(infile);
return elemY;
}
void CFE(float density[], float energy[])
{
FILE *infile;
infile = fopen("test05", "r");
int elemY, elemX;
fscanf(infile, "%i %i", &elemX, &elemY); //Will cause Segmentation break
int n;
float * dens;
dens = density;
float * engy;
engy = energy;
int Length = 10;
for ( n = 0; n < Length; n++)
{
engy[n] = n;
}
}
You need to check that the files are opened correctly - i.e. the the pointer returned by fopen() is not NULL. Also,
int ReturnY ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
return elemX;
}
I take it return elemx should be return elemy?
Any particular reason why you don't just use printf in your C++ code? Sure, it's not like what all the cool kids do, but it should still work.
What platform is this on? If you have ios::sync_with_stdio(bool) available on your platform, call it with
ios::sync_with_stdio(true)
at the beginning of your program (call it from C++). Does this help?
When I mix cout and printf in an application, I find it useful to have all my C++ code do the equivalent of:
fflush(stdout);
cout << ...whatever... << flush;
This way stdout and cout never both have unflushed buffers at any point in time.
Extra care should be taken for apps where multiple threads access stdout and/or cout.
The quick answer here is no, it absolutely 100% should not crash just because you are mixing printf and cout. The only difficulty with mixing the two is that the respective output buffers will not be synced by default, so the order of the output may be a bit mixed up. But it definitely should not crash.
At a quick guess, perhaps you have a formatting problem with printf -- you're passing a double when it expects a short int, or something like that. That will lead to unpredictable problems, which might well shift depending on the order of function calls in your code.
ReturnY() is returning X instead of Y
(ps. close your files)
I don't see a printf(), so I can't comment on it. You should show what printf()s you're using, providing a complete sample program that fails as you describe.
As far as the comment about a crash on fscanf(), as Neil Butterworth says, you need to check the return value of fopen(). If, for some reason, the fopen() fails (which it doesn't look like it should), fscanf() might crash. (If it can't read integers, it should deal with it.) You're not checking anything in I/O. (Alternatively, the I/O system might be messed up from something previous.)
I'd suspect corruption somewhere in the I/O memory, but I don't see enough to conclude anything.