I've looked at similar questions, but being a total newbie at this, they haven't helped much, when I try to run my final if statement I run into this error, how can I make my cout statement clearer? Its intended purpose is to output how many bags of garbage it can accept, how many the user is trying to give it, and how many bags will be left over if it cannot take them all.
while(( reg < 50) && (met< 20) && (glass < 20))
{
reg=reg+reg; met=met+met; glass=glass+glass;
cout<< " I have enough "<< endl;
if(reg+=reg > 50){
cout<< "I can only accept " << 50 - (reg+=reg) << "of your " << (reg+=reg)<<" regular bags of garbage, I'll leave the other " << 50 - (reg+= reg)<< " I'll leave the other " << reg- (50 - reg+=reg)<< endl;
}
50 - reg += reg;
operator+= has lower precedence than operator-. The above statement is interpreted as:
(50 - reg) += reg;
which won't work. You probably wanted:
50 - (reg += reg);
Related
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 2 months ago.
Improve this question
I did not write this code.
i'm on my 3rd day of coding in C++ and i'm having a hard time understanding how incremnent works in general.
int main()
{
int antal_ord {};
double medellangd {};
string kort_ord;
string langt_ord;
int min_length {100};
int max_length {};
string S;
cout << "Mata in en text:\n" << endl;
while (cin >> S)
{
if (S.length() > max_length)
{
max_length = S.length();
langt_ord = S;
}
if (S.length() < min_length)
{
min_length = S.length();
kort_ord = S;
}
medellangd+=S.length();
antal_ord++;
}
if (antal_ord == 0)
{
cout << "Inga ord matades in." << endl;
}
else {
medellangd = (medellangd / antal_ord);
round(medellangd);
cout << "Texten innehöll " << antal_ord << " ord." << endl;
cout << "Det kortaste ordet var " << '"' << kort_ord << '"' << " med "
<< kort_ord.length() << " tecken." << endl;
cout << "Det längsta ordet var " << '"' << langt_ord << '"' << " med "
<< langt_ord.length() << " tecken." << endl;
cout << "Medelordlängden var "<< fixed << setprecision(1) << medellangd << " tecken.";
}
return 0;
}
antal_ord is the variable for the amount of words written in this scenario.
In the line where it says "cout << "Texten innehöll " << antal_ord << " ord." << endl;" how does it know how many words have been written? The only time this variable is used before this line is when the variable gets incremented, but how does that let the variable know how many words have been written in total?
and also the .length command, does it basically just count the amount of letters written?
There's really nothing special going on here. Every time you read one word with cin >> S, you increment antal_ord by one. Since you started with zero words written and antal_ord==0, at the end antal_ord will equal the number of words read from cin.
Similarly, S.length() returns the number of letters currently in S. In your case, that is exactly the number of letters read from cin since you didn't chance S after reading. But if you did S += " some extra letters, then S.length() will of course change.
When you'll learn about most programming languages, you'll start off with basics: syntax, data types, declarations (vars + funcs as well as other possible concepts), loops, calls, math operations and other code-control techniques relevant to each programming language.
What you'll see about most (and I;ll try to "rewind" from the generalization I started with and back down to C/C++) is that you have the following type of math operation variations when it comes to addition (let's focus on this, as it's more on point with the question).
result in a separate variable, in our case b: b = a + 1;
result in the same variable: a += 1;
incrementing the value of the variable: a++;
Expanding on it:
In the first case, b will have its value overwritten and is dependent on a different values (in this case the value of a and 1). What you need to focus on here is that a is NOT changed.
In this case, a receives a new value and is incremented by the right-side-value, in our case 1. a is changed by adding one (not incrementing)
In our case, similar to #2, the value of 8a* is updated, but the incrementation is done by 1.
Apart from syntactic sugar or code style preference, the difference between each is also in the way the variables are assigned their values (more formally said, in the assembly code "underneath"). This topic is a lot more complicated for someone that started programming, but focusing on the question, the answer is simply that ++ increments the value by 1.
Also note that there is a difference in certain coding flows between ++a and a++. Mainly in loops. For ++a the value is set before executing the code, using the already incremented value in the code, while a++ uses the current value of a first, then increments it.
Try it like this:
int i = 0;
while (++i < 100)
{
std::cout << i << std::endl;
}
... versus...
int i = 0;
while (i++ < 100)
{
std::cout << i << std::endl;
}
Then count how many lines each case wrote.
There is also a small caveat you should be aware of, it's a bit more advanced, so it's just a little "FYI" for you. There are two C++ techniques called "function overloading" and "operator (re)definition". Let's focus on the second one. You could build your own data type (for example a struct or class) and implement your own operators that do something other than what their arithmetic counterparts do. You'll see this in iterator definitions. In that case ++ is not "actual value incrementation" (so it's not a math calculation), but rather switching to the next item in a list. Once you reach std::vector lessons you'll encounter that.
I am very new to c++ and I was trying to put together a script that just says how much older/younger someone is than me. The problem is the std::cin isn't working, it's not letting me say the input age. How do I make this work?
#include <iostream>
int main()
{
int age;
int diff = age - 20;
std::cout << "What is your age?\n";
std::cin >> age;
/* There should be an option to say the age, but it goes right into the next code with a random number */
if (diff < 20) {
std::cout << "You are " << diff << " years younger than me.\n";
}
else if (diff > 20) {
std::cout << "You are " << diff << " years older than me.\n";
}
else if (diff = 20) {
std::cout << "You are my age.\n";
}
}
When you say int age;, there's no rhyme or reason to the bits stored in memory that represent that integer. It's undefined behavior, but it will be equal to some random value based on what bits happen to be there. You then use std::cin to store an integer there, which works fine (assuming your code keeps chugging along despite using age before it has a value). Your conditionals then compare diff, which has a random value minus 20, with 20, outputting the right statement based on whatever was stored in diff. For example, when I ran your code, I got the output, "You are -1635346580 years younger than me." To fix this problem, read the value of the user's age before using it like this:
int age;
std::cout << "What is your age?\n";
std::cin >> age;
int diff = age - 20;
Additionally, when you wrote else if (diff = 20), you used an assignment operator. That puts the value of 20 into the variable diff. It then returns that value for use in the expected Boolean. In C++, 0 translates to false, and everything else translates to true. That means, once it gets there, it will always execute since 20 becomes true. Your program will always function correctly, however, since by that point in the code, diff is guaranteed to be 20 since it's neither greater than 20 nor less than 20. You could say else if (diff == 20) to do the comparison, but I'd replace it with else // diff is 20 since you know the value by that point.
Input prompt asks for a starting time, and then a duration time where it returns two times: one time where they are added, and one where they are subtracted. I've gotten the basics of them, but when I try and do it for certain times (ex: 1:18 and 10:39) I get a negative error:
X Input of 1:18 10:39 : expected [11:57, 2:39] but found [11:57, -9:-21]
Here's the code that does the calculations:
int timeHours, timeMinutes, durHours, durMinutes;
cout << " Time: ";
cin >> timeHours;
cin.get();
cin >> timeMinutes;
cout << " Duration: ";
cin >> durHours;
cin.get();
cin >> durMinutes;
int time, duration, after, before, afterHours, afterMinutes, beforeHours, beforeMinutes;
const int MINUTES_IN_DAY = 60 * 24;
time = (timeHours * 60) + timeMinutes;
duration = (durHours * 60) + durMinutes;
after = time + duration;
before = time - duration;
afterHours = after / 60 % 12;
afterMinutes = after % 60;
beforeHours = before / 60;
beforeMinutes = before % 60;
cout << endl;
cout << durHours << ":" << setfill('0') << setw(2) << durMinutes << " hours after, and before, "
<< timeHours << ":" << timeMinutes << " is [" << afterHours << ":" << setw(2) << afterMinutes << ", "
<< beforeHours << ":" << setw(2) << beforeMinutes << "]" << endl;
The failed test above shows that the sum (1:18 + 10:39) works but the difference (1:18 - 10:39) does not work. It gives me "-9:-21" which should be able to be fixed by adding 24 hours, which is even what my assignment suggests: "This is easily done by adding a day (or two or three) to before when calculating the difference" but when I add 1440 (60 * 24) to the "before" initialization:
before = (time - duration) + MINUTES_IN_DAY;
and convert back from minutes to normal time I get 14:39, which is 2:39, but in 24 hour form, not 12 (incidentally it also makes all the other tests which were passing now failing). I think there's some hint when it says "by adding a day (or two or three) since obviously 1440 is different from 1440*2 or *3, but I'm not seeing it and I have to be missing something obvious. I know I'll have to fix it for midnight as well but I'll change that later. If anyone knows what I'm trying to explain, I'd really appreciate it
Usually, when working with times/dates it's easier to make yourself a function to convert a human-readable date to milliseconds or seconds (and vice versa) and build up from that base. In your case, you'll just add/subtract the two time-marks in seconds for example:
long long time = toSec(timeHours, timeMinutes, timeSeconds);
long long duration = toSec(durHours, durMinutes, durSeconds);
string after = toDate(time + duration);//somethig like 12:34:00 (hh:mm:ss)
string before = toDate(time - duration);
however, putting effort in making such conversion functions would be an overcomplication if all you use them for is a one-time calculation.
( like you suggested to add MINUTES_IN_DAY) to solve the negative values problem you can use the %MINUTES_IN_DAY to avoid the overflow caused by adding MINUTES_IN_DAY to a positive value
before = ((time - duration)+MINUTES_IN_DAY)%MINUTES_IN_DAY;
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
friends. I have a problem.
Problem: the computer must pick randomly one string out of an array of 36 strings. If by any chance it picks strings #34 or #35 (the two last ones), it has to draw two more random strings from the same array. I tried a do-while solution, and it "almost" works (see code below).
The randomization works fine - called srand inside main(). There is a forced "x2" draw (for testing reasons), so the computer draws two more strings. These two new random picks are NOT "x2", but still the loop kicks again - but just one more time! This time the computer picks two more "chits", which aren't "x2" either, so, as expected, it returns the "The chits have been drawn" sentence and the function is terminated. Why is the same code running twice with the same results but different if/else behavior? Thank you very much in advance.
string mortalityCalc ()
{
string mortalityChits[36] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","-","-","-","-","x2","x2"};
int mortalityResult;
// mortalityResult = rand() %36;
mortalityResult = 35; // for testing only. Delete afterwards.
string drawnChit = mortalityChits[mortalityResult];
string drawnChit1;
string drawnChit2;
if (drawnChit != "-" && drawnChit != "x2")
{
string returnText = string("The computer has drawn the chit '") + drawnChit + "'.";
return returnText;
}
else if (drawnChit == "-")
{
string returnText = string("The computer has drawn the chit '") + drawnChit + "'. No senators died this year.";
return returnText;
}
do
{
cout << "The computer has drawn the 'x2' chit." << endl;
cout << "Two more chits will be drawn.\n" << endl;
mortalityResult = rand() %36;
drawnChit1 = mortalityChits[mortalityResult];
cout << "The first draw is the chit '" << drawnChit1 << "'. ";
mortalityResult = rand() %36;
drawnChit2 = mortalityChits[mortalityResult];
cout << "The second draw is the chit '" << drawnChit2 << "'." << endl;
} while (drawnChit1 == "x2" || drawnChit2 == "x2");
return "The mortality chits have been drawn. The corresponding senators are dead.";
}
UPDATE: Tried running this code isolated from the rest of the program and it behave as expected. So I guess it's important to post what comes before it:
cout << "If you are a lazy bastard, the computer can pick one senator randomly for you.\nAre you a lazy bastard? [y/n]" << endl;
string lazyBastard;
cin >> lazyBastard;
cout << endl;
if (lazyBastard == "y" || lazyBastard == "Y" || lazyBastard == "yes" || lazyBastard == "YES" || lazyBastard == "Yes")
{
mortalityCalc ();
cout << mortalityCalc () << endl;
cout << "Very well. Now, imminent wars become active (Only one of each match)." << endl;
cout << "Get ready for the next phase." << endl;
My guess, from reading some other questions here, is that somehow the cin is messing with the loop behavior, even though they are not related and there's no user input whatsoever in the loop's statements or conditions. Is that possible? If so, why and how to remedy it?
Thank you again.
In the first loop you are forcing an 'x2' so your are entering the do-while loop. The result of the two calls for 'rand())%36' is always 19 and a number between 30 and 34. The point is that the random number generator generates always the same sequence of numbers, if you don't give him a seed 'srand(...)'.
do {
// ...
cout << rand()%36;
// ...
} while( /*...*/ )
See http://ideone.com/zl8ggH
You have to create random numbers and your code does what you expect.
Finally! I thought it would be a stupid thing! I just realized that I called the mortalityCalc() function twice! That's why it was looping twice!
Thanks to all who tried to help!