This question already has answers here:
Delay execution 1 second
(4 answers)
Closed 8 years ago.
I need a timer that does X every second.
I made this, however it doesn't print anything until the program is terminated, I find that weird.
It prints everything after three seconds if you put three as the counter, and 100 if you chose that.
How do make it print every second and not all at once at termination?
int main()
{
using namespace std;
//Number to count down from
int counter = 10;
//When changed, a second has passed
int second = (unsigned)time(NULL);
//If not equal to each other, counter is printed
int second_timer = second;
while (counter > 0) {
second = (unsigned)time(NULL);
while (second != second_timer) {
//Do something
cout << counter-- << ", ";
//New value is assigned to match the current second
second_timer = second;
}
}
cout << "0" << endl;
return 0;
}
Add << flush where you want to flush. I.e. change your printout to:
cout << counter-- << ", " << flush;
endl causes the buffer to 'flush' and be written out to stdout. You can add << endl; to your cout << counter--, manually flush the cout stream using cout.flush();, or append << flush; to the end of your cout expression (thanks #Rob!)
For more info, the answer to this question seems to go into more detail.
Related
This question already has answers here:
C++ "return" without value [closed]
(7 answers)
Closed 6 months ago.
I couldnot find a logical reason as how this return statement is working. As much as i read,it should return undefined but the program takes it straight to the recursive call
function below
#include <iostream>
using namespace std;
// Recursive function to print the pattern without any extra
// variable
void printPattern(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}
// Driver Program
int main()
{
int n = 16;
printPattern(n);
return 0;
}
the output of above code is
16 11 6 1 -4 1 6 11 16
Recursion isn't special. Here's your function again, but I hid the name so you can't see which function it is.
void XXXXXXXXXX(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}
What does XXXXXXXXXX(-1) do? That's right: it prints -1
What does XXXXXXXXXX(16) do? That's right: it prints 16, then it prints the pattern for 11, then it prints 16 again.
Now can you see why XXXXXXXXXX(16) prints 16 at the start and the end?
return (irregardless if the function is recursive or not) will pass an optional value to caller, and execution will then continue in caller.
I have a file that has 3 columns with many rows. I want to compare the value either increase or decrease for 2 columns. But when I compare, the value always increases even it should be decreased. Any idea how to solve this? This is my coding to compare the value in the file. But I didn't get the desired output. anyone can help me?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fromFile;
fromFile.open("data.txt");
{
cout << "There was an error" << endl;
exit(1);
}
else
cout << "No error, file opened successfully" << endl;
fromFile.clear();
fromFile.seekg(0);
for(int i=1; i<=20; i++)
{
int a{}, b {}, c {};
fromFile >> a >> b >> c ;
cout<<" Year : " <<a<<" population : "<<b<<" car : "<<c<< endl;
if ( b < b && c < c )
cout << " population decrease and car production decrease " << endl;
if ( b > b && c > c );
cout << " population increase and car production increase " << endl;
if ( b > b && c < c )
cout << " population increase but car production decrease " << endl;
if ( b < b && c > c );
cout << " population decrease but car production increase " << endl;
}
//CLOSES FILES
fromFile.close();
return 0;
}
There are several problems with your code. I will first mention those and then show a corrected solution (one of many possible variants).
Some issues:
You should not use using namespace std. There are many expanations on stackoverflow with the explanation. Use full qualified names instead
The std::ifstream has a constructor that automatically opens the stream. No need for function open
The stream has an overloaded bool operator. You can simply test the state with if (fromFile)
You forgot the if statement, but have an else statement. So, your program will not compile. And is logically wrong
Because of the missing if the program will always exit immidiately
clear and seekg are not necessary. The filepointer is at the beginning after opening the stream.
You use a loop with fixed hardcoded magic number 20. What if the file has more or less rows? You need to use the condition end-of-file to end the loop
You compare always the variables with itself. Even the compiler will warn you. This cannot work. You need to read a variable, store it somewhere in a different variable, read again from the file and compare the current variable with the previous value. This is your main problem
No need to call the close-function of the stream. The destructor will call it implicitely for you, when the stream variable leaves its scope
You have not enough comparision if statements. Many cases, especially, if values are same than before, will not be handled
So, what do we need to do? I will explain with only one variable now. Let's take the year. We define a variable year and a second varibale previousValueYear. In a loop, we read the value from the file into year. Then, we compare the year variable with the previousValueYear, do the evaluation and show the output. And then, before reading the next value from the file, we copy the current value from year to previousValueYear. Then we can do the correct comparison in the next loop run.
The first comparision is a little bit tricky, because we do not have a previousValueYear. We will add an additional if statement with a boolean flag, to check for this condition.
Please see here the corrected version:
#include <iostream>
#include <fstream>
int main() {
// Open the source file
std::ifstream fromFile("data.txt");
// Check, if we could open the file
if (fromFile) { // bool operator of stream will be called
// OK, file could be opened. Defineour variables
int year{}, population{}, car{};
int previousValueYear{}, previousValuePopulation{}, previousValueCar{};
bool thisIsTheNotFirstLoopRun{};
// Read values in a loop and check, if the input worked
while (fromFile >> year >> population >> car) {
// Show read data
std::cout << "Year: " << year << " \tPopulation: " << population << " \tCar: " << car << '\n';
// In the first loop run, we will not do a comparision (There is only one value and nothing to compare
if (thisIsTheNotFirstLoopRun) {
// Do the comparisons
if ((population < previousValuePopulation) and (car < previousValueCar))
std::cout << "Population decrease and car production decrease\n";
if ((population > previousValuePopulation) and (car > previousValueCar))
std::cout << "Population increase and car production increase\n";
if ((population > previousValuePopulation) and (car < previousValueCar))
std::cout << "Population increase and car production decrease\n";
if ((population < previousValuePopulation) and (car > previousValueCar))
std::cout << "Population decrease and car production increase\n";
}
// Remember current values for next loop run
previousValueYear = year;
previousValuePopulation = population;
previousValueCar = car;
// Now, we will not have any longer the first loop run
thisIsTheNotFirstLoopRun = true;
}
}
else {
// Error, file could not be opened. Show message
std::cerr << "\nError: SourceFile could not be opened\n";
}
return 0;
}
Advanced C++ porgrammers would change a lot. But for now it is OK
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Tried several times yet still didnt manage to find my mistake: here is my program. i need to find the odd numbers from 1 and integer x and find the sum of them cubed.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x;
int i = 1;
int result;
cout <<" Enter the value for n" << endl;
cin >> x;
while (i >x)
if (i%2 == 0) {}
else {
result += pow(i,3);
i++;
}
cout << "The sum of odd integers cubes from " << i << " to " << x << "= " << result << endl;
return 0;
}
Minimally, you should change the compare in while
from
while (i > n)
to
while (i <= n)
There a many numbers where i will be greater than the number entered, n.
You didn't add in your curly brackets for the while loop.
while (i > x)
if (i%2 == 0) {}
needs to be:
while (i > x){
if (i % 2 == 0) {}
}
Plus what are you doing inside of that if statement? You should decrement x, to find if each number is odd.
Plus, your program ends early because i is 1 and if the user enters a number above 1, your while loop won't even run. You're telling the while loop to run ONLY when i is larger than x. Try changing it to less than:
from:
while (i > x){
to:
while (i < x){
Plus you're not doing anything with x. You want to decrement x, not add i. Although, I would recommend using a do-while loop. ( a dowhile loop does one iteration first before incrementation)
do{
if (x % 2 == 0) { // if the remainder of x/2 is 0, do this
x--;
cout << "Equal: " << x << endl;
}
if(x % 2 != 0) { //if the remainder of x/2 is not 0, do this.
temp = pow(x,3);
//you don't want to take the power of the added sum,
//you were taking the power 3 of x which was being added to.
//you want to add the sums of each power. So here we have temp, a
//temporary variable to store your addends.
result = result + temp;
cout << "Not equal, temp:" << temp <<endl;
cout << "Result: "<< result << endl;
x--; //you didn't have a decrement, you need to bring x eventually down to i if you want the loop to end, or even look through all of the numbers
}
}
while (i < x);
//You have to have this semi colon here for the compiler to know its a do-while.
cout << "The sum of odd integers cubes from " << i << " to " << userVar
<< " = " << result << endl;
return 0;
}
note: if-else statements are for flow control, its like true and false, one or the other, so that your data will flow somewhere. I used two if statements because I want to have complete control over the flow.
note2: It's ok to use:
using namespace std;
at first, but eventually you want to start learning what library each command is using. When you get into more complex programming, you start using commands from different libraries than the standard one.
I am making a program in C++, that takes the user entered time in U.S. standard time and converts it to military time. The body of the main code is executing fine, but the problem comes in the body of my function beginning with the if statements. I am wondering why this is occurring; am fairly new with c++. Here's my code if you have question feel free to ask or need explanation of what the program is supposed to be doing.
#include <iostream>
#include <string>
using namespace std;
void militaryConversion(string am_pmPart_st, string firstPartofTime, string secondPartofTime){
// Converts they obtained strings, but first we must concatenate the two parts into one string
string concatenatedTime;
int militaryTime;
cout << "test1" << endl;
concatenatedTime = firstPartofTime + secondPartofTime;
if(firstPartofTime == "12")
{
cout << "Corresponding military time is: " << concatenatedTime << " hours" << endl;
}
else if(am_pmPart_st == " am")
{
if (concatenatedTime.length() < 4){
cout << "Corresponding military time is: " << concatenatedTime << " hours"<< endl;
}
}
else if(am_pmPart_st == " pm")
{
int castedTime;
castedTime = stoi(concatenatedTime); //This is where we convert the string to int because its the only place it matters
militaryTime = castedTime + 1200;
cout << "Corresponding military time is: " << militaryTime << " hours" << endl;
}
}
int main()
{
char DELEMETER = ':';
char DELEMETER_sp = ' ';
string time, firstPartofTime, secondPartofTime, am_pmPart_st, loweredAM_PM;
cout << "Enter the time in the format of: HH:MM AM/PM ";
getline(cin, time);
firstPartofTime = time.substr(0, time.find(DELEMETER));
cout << "The first digits of time " << firstPartofTime << endl;
secondPartofTime = time.substr(time.find(DELEMETER) + 1, time.find(DELEMETER_sp)-1);
cout << "The second set of digits " << secondPartofTime << endl;
am_pmPart_st = time.substr(time.find(DELEMETER_sp), time.size());
cout << "The am/pm part is:" << am_pmPart_st << endl;
for(int i=0; am_pmPart_st[i]; i++) am_pmPart_st[i] = tolower(am_pmPart_st[i]); //Converts am/pm to lowercase
cout << am_pmPart_st << endl;
militaryConversion(am_pmPart_st, firstPartofTime, secondPartofTime);
}
First, your question is vague because it does say what is happening that should not be happening. However, I think I can see what is happening. When you check for the hour part of the time in the first condition, you check for "12" first. However, you never correct for am or pm within that 12. My recommendation would be to check for 12 inside the am (12 am == 0000 hours) and pm (12 pm == 1200 hours). In am you will need to check for 12 and subtract 1200 from the time, in pm you will need to check for 12 and not add 1200 to the time.
substr takes two parameters. The first is the start position and the second is the length. When you call secondPartofTime = time.substr(time.find(DELEMETER) + 1, time.find(DELEMETER_sp)-1); you are mistakenly passing the second parameter as the end position, not the length.
Instead, you can do:
int startPos = time.find(DELEMETER) + 1;
int endPos = time.find(DELEMETER_sp) - 1;
secondPartofTime = time.substr(startPos, endPos - startPos + 1);
Ideally, you should check the return values of find and handle the case when npos is returned so you don't crash on invalid user input.
Input which doesn't follow the HH:MM AM/PM form is creating a problem. (Exactly 5 characters for HH:MM (including colon))
You have an if-else based decision tree, where one if is not accompanied by an else. The lack of else is why your program is not giving any output
string.substr() has some issues as explained by MFisherKDX
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a function that is being used to calculate the damage caused towards an object
string Weapon::attack(int Damage, int ExtraDamage, string Type)
{
srand(time(NULL));
int totalDamage = 0;
int percentileDie = rand() % 100 + 1;
if (percentileDie <= ChanceToHit) {
for (int i = 0; i <= Damage; i++)
{
int sixSidedDie = rand() % 6 + 1;
totalDamage = totalDamage + sixSidedDie;
}
totalDamage = totalDamage + ExtraDamage;
}
else {
totalDamage = 0;
}
Result = totalDamage;
if (Type == "Crossbow") {
return "Twang! ";
}
else if (Type == "Dagger" || Type == "Sword") {
return "Swing! ";
}
}
However, when I go and call the variable Result in my program, I get the number -858993460. I changed Result = totalDamage to Result = 6 to see if it would return 6 but it once again returned -858993460.
Can anyone help me out?
If I do this:
Weapon t;
t.attack(2, 4, "Sword");
cout << t.attack(2, 4, "Sword") << t.Result << endl;
I get the correct number, but if I do this:
Weapon t;
cout << t.attack(2, 4, "Sword") << t.Result << endl;
I get the number -858993460 again!
Also, Result is declared in a class:
class Weapon {
public:
string Name;
int Damage, ExtraDamage, Result;
float ChanceToHit;
string attack(int,int,string);
};
The order of evaluation of cout << X << Y is not ordered for X and Y.
So this code:
Weapon t;
cout << t.attack(2, 4, "Sword") << t.Result << endl;
will evaluate either t.attack() or t.Result first - based on your post, it would seem that t.Result is evaluated first.
The solution is to force the compiler to do things in the correct order, e.g.
Weapon t;
std::string str = t.attack(2, 4, "Sword");
cout << str << t.Result << endl;
If you look into what exactly is going on here, then you will realize that operator "<<" is being used to add data to output stream.
The "<<" operator is defined to add data on stream and return a reference of modified stream for further use, this is the reason we can use multiple "<<" in single "cout" So the order of putting values on stream is reverse of the order in which you read it.
So it is like
cout<<firstOperand<<secondOperand<<thirdOperand;
is evaluated as
cout(<<firstOperand(<<secondOperand(<<thirdOperand)));
Which in turn means that "thirdOperand" is added to output stream first then updated stream is returned. Now "secondOperand" is pushed to the same returned stream similarly and then "firstOperand" is pushed to the output stream. Now all "<<" operators are done. Now cout puts the stream content on the output file.
So, in your case, because t.Result is getting added to output stream before its calculation in class function, the value that you get is random value of Result initialized during object construction.