• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 21:45
CEST 03:45
KST 10:45
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL20] Ro24 Preview Pt2: Take-Off7[ASL20] Ro24 Preview Pt1: Runway132v2 & SC: Evo Complete: Weekend Double Feature4Team Liquid Map Contest #21 - Presented by Monster Energy9uThermal's 2v2 Tour: $15,000 Main Event18
Community News
Weekly Cups (Aug 18-24): herO dethrones MaxPax6Maestros of The Game—$20k event w/ live finals in Paris34Weekly Cups (Aug 11-17): MaxPax triples again!13Weekly Cups (Aug 4-10): MaxPax wins a triple6SC2's Safe House 2 - October 18 & 195
StarCraft 2
General
A Eulogy for the Six Pool BoxeR's Wings Episode 2 - Fan Translation Greatest Players of All Time: 2025 Update #1: Maru - Greatest Players of All Time Geoff 'iNcontroL' Robinson has passed away
Tourneys
$5,000 WardiTV Summer Championship 2025 Maestros of The Game—$20k event w/ live finals in Paris $5,100+ SEL Season 2 Championship (SC: Evo) Esports World Cup 2025 Sparkling Tuna Cup - Weekly Open Tournament
Strategy
Custom Maps
External Content
Mutation # 488 What Goes Around Mutation # 487 Think Fast Mutation # 486 Watch the Skies Mutation # 485 Death from Below
Brood War
General
Post ASL20 Ro24 discussion. BGH Auto Balance -> http://bghmmr.eu/ No Rain in ASL20? How do I speak directly to Coinbase?1-(888)-419-97 Recent recommended BW games
Tourneys
[IPSL] CSLAN Review and CSLPRO Reimagined! [ASL20] Ro24 Group D [ASL20] Ro24 Group E Small VOD Thread 2.0
Strategy
Muta micro map competition Simple Questions, Simple Answers Fighting Spirit mining rates [G] Mineral Boosting
Other Games
General Games
Stormgate/Frost Giant Megathread General RTS Discussion Thread Nintendo Switch Thread Dawn of War IV Path of Exile
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread The year 2050 European Politico-economics QA Mega-thread
Fan Clubs
INnoVation Fan Club SKT1 Classic Fan Club!
Media & Entertainment
Anime Discussion Thread Movie Discussion! [Manga] One Piece [\m/] Heavy Metal Thread
Sports
2024 - 2026 Football Thread Formula 1 Discussion TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread High temperatures on bridge(s) Gtx660 graphics card replacement
TL Community
The Automated Ban List TeamLiquid Team Shirt On Sale
Blogs
How Culture and Conflict Imp…
TrAiDoS
RTS Design in Hypercoven
a11
Evil Gacha Games and the…
ffswowsucks
INDEPENDIENTE LA CTM
XenOsky
[Girl blog} My fema…
artosisisthebest
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2362 users

Help with programming in C++

Blogs > KiLL_ORdeR
Post a Reply
Normal
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
Last Edited: 2010-10-08 14:35:12
October 07 2010 19:10 GMT
#1
Hi all,

I've noticed over the year or so that i've been a member of Team Liquid that there are quite a few Computer Science people in the community. I'm a digital art major in University so I have to take Computer Science classes to supplement the Digital part.

Right now I'm taking an intro to C++ class and I'm trying to prepare for the midterm, which involves going into class and writing programs. I'm a little over my head I think. I understand the real basic stuff, like compiling, a few basic programs, and conceptually how the software works, but I'm having trouble making programs do what I want them to do. It would be really awesome if people here who know more than I do could help me out a bit, since I'm running out of time.

We use Wascana Eclipse, and out textbook is Starting Out with C++: From Control Structures through Objects by Tony Gaddis, if that matters to anyone. What I'm going to do is write down each separate problem, and then include code i've written so far, and what I specifically need help with. Here are the problems I am having trouble with:

Area of Rectangles

*Write a Program that asks the user for the length and width of two rectangles. The program should tell the user which rectangle has a larger area, or if they are the same.


+ Show Spoiler [Code so far] +

#include <iostream>
using namespace std;

int main()

{
int length, width, area1, area2;

// First Rectangle
cout << "What is the length of the first rectangle? ";
cin >> length;
cout << "What is the width of the first rectangle? ";
cin >> width;
area1 = length * width;
cout << "The area of the first rectangle is " << area1 << ".\n";

// Second Rectangle
cout << "What is the length of the second rectangle? ";
cin >> length;
cout << "What is the width of the second rectangle? ";
cin >> width;
area2 = length * width;
cout << "The area of the second rectangle is " << area2 << ".\n";

//Comparison
if (area1>area2){
cout << "The first triangle is larger\n";
}
else if (area1<area2){
cout << "The second rectangle is larger\n";
}
else if (area1==area2){
cout << "They are equal\n";
}

return 0;
}


Finally got it to work


Math Tutor
*Write a program that displays two random numbers in this format:

74
+ 12

The program should wait for the student to enter the correct answer. If the answer is correct, a message of congratulations should be printed. If incorrect, the message should show the correct answer.

+ Show Spoiler [Code so Far] +

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()

{
unsigned seed = time(0);
srand (seed);

int randa, randb, total, answer;
randa = rand ()%50;
randb = rand ()%50;
total = randa+randb;

cout << " " << randa << endl;
cout << "+ " << randb << endl;
cout << "______\n";
cout << "please enter what you think is the correct answer:\n";
cin >> answer;

if (answer==total){
cout << "you are correct :)";
}
else{
cout << "Sorry, you're wrong this time :(\n";
cout << "The correct answer is " << total << endl;
cout << "Double check your answer, then try again with new numbers";
}

return 0;
}


Finally got this one right. I also think I'm finally getting the hang of an if else statement.


EDIT: These are the last problems

Ocean Levels
*Assuming that the Oceans level is rising 1.5 millimeters per year, write a program that displays a table showing the number of millimeters that the Ocean will have risen each year for the next 25 years.

+ Show Spoiler [Code so Far] +

#include <iostream>
using namespace std;

int main()

{
int years = 0;
cout << "Years Growth\n";
cout << "_____________________\n";
while (years <= 25)
{
cout << years << "\t\t" << (years + 1.5) <<endl;
years++;
}
return 0;
}

This one isn't doing what it's supposed to do. Instead of adding 1.5 each loop, it's instead starting at 1.5 and adding one. Gonna look back I think I just need to change years++


The Greatest and Least of These
*Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all of the numbers have been entered, the program should display the largest and smallest numbers entered.

+ Show Spoiler [Code so Far] +


I'm obviously like an E- computer noob at programming, but I actually kinda like it, and I really like the feeling of making a program actually work. If anyone is able to help me either with advice, useable code, etc. it would be very much appreciated.

In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
tofucake
Profile Blog Joined October 2009
Hyrule19082 Posts
Last Edited: 2010-10-07 19:24:33
October 07 2010 19:14 GMT
#2
On October 08 2010 04:10 KiLL_ORdeR wrote:
Hi all,

I've noticed over the year or so that i've been a member of Team Liquid that there are quite a few Computer Science people in the community. I'm a digital art major in University so I have to take Computer Science classes to supplement the Digital part.

Right now I'm taking an intro to C++ class and I'm trying to prepare for the midterm, which involves going into class and writing programs. I'm a little over my head I think. I understand the real basic stuff, like compiling, a few basic programs, and conceptually how the software works, but I'm having trouble making programs do what I want them to do. It would be really awesome if people here who know more than I do could help me out a bit, since I'm running out of time.

We use Wascana Eclipse, and out textbook is Starting Out with C++: From Control Structures through Objects by Tony Gaddis, if that matters to anyone. What I'm going to do is write down each separate problem, and then include code i've written so far, and what I specifically need help with. Here are the problems I am having trouble with:

Area of Rectangles

*Write a Program that asks the user for the length and width of two rectangles. The program should tell the user which rectangle has a larger area, or if they are the same.


+ Show Spoiler [Code so far] +

#include <iostream>
using namespace std;

int main()

{
int area1, area2;

{
int length, width, area1, area2;

// First Rectangle
cout << "This program calculates the areas of two";
cout << "rectanlges, and then compares the two and";
cout << "displays which one is larger.\n";
cout << "What is the length of the first rectangle? ";
cin >> length;
cout << "What is the width of the first rectangle? ";
cin >> width;
area1 = length * width;
cout << "The area of the first rectangle is " << area1 << ".\n";

// Second Rectangle
cout << "What is the length of the second rectangle? ";
cin >> length;
cout << "What is the width of the second rectangle? ";
cin >> width;
area2 = length * width;
cout << "The area of the second rectangle is " << area2 << ".\n";

}
if (area1 > area2);
{
cout << "The first rectangle is larger than the second one.\n";
else (area1 < area2);
cout << "The second rectangle is larger than the first one.\n";
return 0;
}


I really thought that this one would work, I have no idea why it won't compile I get an error message that says "else without previous if" and "expected '}' at end of input" both of which are things I have.


Math Tutor
*Write a program that displays two random numbers in this format:

74
+ 12

The program should wait for the student to enter the correct answer. If the answer is correct, a message of congratulations should be printed. If incorrect, the message should show the correct answer.

+ Show Spoiler [Code so Far] +
I don't have anything written for this one yet, but I do know how to make two random number, within any range I want. I also understand that I need to use an if-else statement to complete the program. What I can't figure out how to do is to get the number to print in that format, and how to add the two random numbers.


Running the Race
*Write a prgoram that asks for the names of 3 runners, and the time it took for them to finish a race. The program should display who cam in 1st, 2nd, and 3rd, and times should not have negative values.

+ Show Spoiler [Code so Far] +
We did something similar to this in class, but it was only using two names. When I was trying to do this with three names, it seems that the logic is much different. Additionally, I was unsure how to get the names to bind with the times.


Sum of Numbers
*Write a program that asks the user for a positive integer. The program should contain a loop to get the sum of all of the numbers from 1 to the number the user entered. For example, if the user enters fifty, the program should get the sum of all numbers from 1 through 50. Do not accept negative numbers.

+ Show Spoiler [Code so Far] +
#include <iostream>
using namespace std;

int main ()
{
{
int number;

cout << "Please enter a number." << endl;
cout << "Make sure that your number is a positive integer.";
cin >> number;
{

int x = number;
while (x > 2)
x = x - 1;
}
}


return 0;
}


So ya. I'm really stumped on this one. I know how to retrieve a number, and I think I understand the mechanics of a while loop, but I have know idea how to get the sum, or prevent the use of negative numbers.


I addition to these, there are two more problems I'm trying to work through, I'll update with questions as they arise.

I'm obviously like an E- computer noob and programming, but I actually kinda like, and I really like the feeling of making a program actually work. If anyone is able to help me either with advice, useable code, etc. it would be very much appreciated.


Okay, for area of rectangles: braces should match. You randomly tossed in an opening brace between some declarations. Also, if you do if(blah) { you need to use } else. There are two ways to do if-else blocks. 1: No braces, 2: Braces. When not using braces, you can only have 1 statement between the condition and the else. When using braces, you can do as much as you want. You can mix and match as well, to do something like

if(a == 1)
cout << "stuff";
else {
cout << "OMG";
cout << "WTF";
cout << "BBQ";
}


Math Tutor
int a = rand()
int b = rand()
int sum = a+b

cout << " " << a << endl;
cout << "+ " << b << endl;
cout << "------" << endl;


It's only pseudocode, so replace rand() with your real number generator.

Running the Race
Use 3 variables for times and 3 variables for runner names (strings or char arrays, however you've been taught). runnera/timea, runnerb/timeb, etc... The logic for comparing 3 variables is exactly the same as for comparing 2, it just looks harder.

Summing Numbers
while(counter < number) sum += counter++;

Also, you REALLY need to stop throwing braces around all willy-nilly.
Liquipediaasante sana squash banana
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 07 2010 19:18 GMT
#3
ah thanks, that does actually make it a bit easier.
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
Slithe
Profile Blog Joined February 2007
United States985 Posts
Last Edited: 2010-10-07 19:25:34
October 07 2010 19:20 GMT
#4
The else statement is contained within the the if block. The syntax is supposed to be like this:


if (statement)
{
(block of code)
}
else
{
(block of code)
}


edit:
Also, you don't want the semicolons at the end of the line for your if and else statements.

I would also expect an error because you're re-declaring area1 and area2.
Shivaz
Profile Blog Joined March 2009
Canada1783 Posts
October 07 2010 19:25 GMT
#5

int x, i, sum;
cin >> x
while (x < 0 )
{
cout << " please enter pos number" << endl;
cin >> x;
}

for (i = 0; i < x+1; i++)
{
sum = sum + i;
)

cout << sum << endl;


number 4, if i didnt make any dumb mistakes
tofucake
Profile Blog Joined October 2009
Hyrule19082 Posts
October 07 2010 19:27 GMT
#6
On October 08 2010 04:25 Shivaz wrote:

int x, i, sum;
cin >> x
while (x < 0 )
{
cout << " please enter pos number" << endl;
cin >> x;
}

for (i = 0; i < x+1; i++)
{
sum = sum + i;
)

cout << sum << endl;


number 4, if i didnt make any dumb mistakes

Same with OP (probably should mention this in my reply...), but if they enter a negative number your program will loop forever. Also, instead of using i < x + 1, you should use i <= x. You can also do sum++ instead of sum = sum + 1
Liquipediaasante sana squash banana
Marradron
Profile Blog Joined January 2009
Netherlands1586 Posts
October 07 2010 19:34 GMT
#7
I don't see the point of telling you how to do these simple programs. You seem to make basic syntacs error in the most basic if and if else loops. Have you actually tried debugging and reading error messages ? Or tried running in debug mode.

The point I'm making you either didn't study the basic syntax well or just didn't study or practice enough. I'm not just talking about the syntacs but also proper programming You have a spamline of 10 couts while you can just write your message in one line instead of splitting it up in 10. You can also request the input of both rectanguals in either one message or 2 if you really want to split both up.

A few small notes. Why restric the size of those rectangulars to ints they could have any size.


Your else loop is wrong. You enter another statement namely area2 > area1. Else loops are run without restraints if the if fails. What you were like for is a else if loop. Even in that case your program could be wrong. What happens if both areas are the same.
tofucake
Profile Blog Joined October 2009
Hyrule19082 Posts
October 07 2010 19:40 GMT
#8
What are you smoking? "Else loop"?
Liquipediaasante sana squash banana
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
October 07 2010 19:40 GMT
#9
Disclaimer: Haven't done C++ in a while so you'll have to double check for errors etc, code meant to be used as examples not directly implemented.


// rectangle one:
if (area1 > area2);
{
cout << "The first rectangle is larger than the second one.\n";
}
else (area1 < area2);
{
cout << "The second rectangle is larger than the first one.\n";
}
return 0;


For the random numbers one, something like this

int num1 = rand();
int num2 = rand();
cout << num1 << "\n+" << num2 << endl;
cin >> answer;

if ( answer == (num1+num2) )
{
cout << "gz";
}
else
{
cout << "Sorry the wrong answer is: " << num1+num2 << endl;
}


For the runners there are several methods, but I think your prof wants you to take a look at sorting algorithms, maybe? As an itroduction... There are very very many different ones. Maybe he just straight wants you to compare them, like so:


if (runner1 > runner 2 && runner1 > runner3)
{
runner 1 wins!
}


Or hell maybe he wants you to make a runner class... I doubt it though.

class Runner {
int time;
}

Runner jack;
jack.time = 10;


As for storing the names + times, you could use a 2d array.

int runners[name][time] = {
A, 1,
B, 2,
C, 3
};


You'll have a matrix looking like this

0,0 | 0,1
-----------
1,0 | 1,1
-----------
2,0 | 2,1

or

A | 1
-------
B | 2
-------
C | 3

The thing about "not negative values" either means you have to validate the input (i.e. check if it's a positive integer or not, for this you could use an ascii chart and check if each character in the input string is in the area you want, if that makes sense...) OR it could mean that the user will only input positive integers, in which case don't worry about it, and I assume that's what he means as these are beginner tasks.

Now, let's have a look at the loop one.
First off cin >> int is dangerous, but I think you shouln't worry about that now as in the above question the user will probably only input positive integers so let's just assume that (not good practice but w/e).

your loop should look something like this:

cin >> number;
int x = 0;
while (x < number)
{
x++;
} // this will loop until X = number

alternatively a more pretty loop would be

for (int x = 0; x < number; x++)
{
// do whatever here.
}


for loops are cool -

for ( variables; condition; increment/decrement )


these can be mixed and matched however you want, and you can leave some of them blank if you want, here's an infinite loop:

for (;;).
Shivaz
Profile Blog Joined March 2009
Canada1783 Posts
October 07 2010 19:42 GMT
#10
On October 08 2010 04:27 tofucake wrote:
Show nested quote +
On October 08 2010 04:25 Shivaz wrote:

int x, i, sum;
cin >> x
while (x < 0 )
{
cout << " please enter pos number" << endl;
cin >> x;
}

for (i = 0; i < x+1; i++)
{
sum = sum + i;
)

cout << sum << endl;


number 4, if i didnt make any dumb mistakes

Same with OP (probably should mention this in my reply...), but if they enter a negative number your program will loop forever.


yeah exactly keep asking until they enter a positive number. isn't that what the program wants
Scorcher2k
Profile Joined November 2009
United States802 Posts
Last Edited: 2010-10-07 19:45:43
October 07 2010 19:43 GMT
#11
On October 08 2010 04:34 Marradron wrote:
I don't see the point of telling you how to do these simple programs. You seem to make basic syntacs error in the most basic if and if else loops. Have you actually tried debugging and reading error messages ? Or tried running in debug mode.

The point I'm making you either didn't study the basic syntax well or just didn't study or practice enough. I'm not just talking about the syntacs but also proper programming You have a spamline of 10 couts while you can just write your message in one line instead of splitting it up in 10. You can also request the input of both rectanguals in either one message or 2 if you really want to split both up.

A few small notes. Why restric the size of those rectangulars to ints they could have any size.


Your else loop is wrong. You enter another statement namely area2 > area1. Else loops are run without restraints if the if fails. What you were like for is a else if loop. Even in that case your program could be wrong. What happens if both areas are the same.

I seriously doubt he has been shown how to debug. Reading error statements or even knowing where you can read them isn't second nature to people just starting out. His code wasn't that bad and it could be just how his professor wanted him to do it.
On October 08 2010 04:42 Shivaz wrote:
Show nested quote +
On October 08 2010 04:27 tofucake wrote:
On October 08 2010 04:25 Shivaz wrote:

int x, i, sum;
cin >> x
while (x < 0 )
{
cout << " please enter pos number" << endl;
cin >> x;
}

for (i = 0; i < x+1; i++)
{
sum = sum + i;
)

cout << sum << endl;


number 4, if i didnt make any dumb mistakes

Same with OP (probably should mention this in my reply...), but if they enter a negative number your program will loop forever.


yeah exactly keep asking until they enter a positive number. isn't that what the program wants

It doesn't matter if they user intentionally tries to muck the program. The instruction is to only account for users who follow instructions so there is no need to program it for the 'what if'. This is really just a very easy intro class level program.
TossFloss *
Profile Blog Joined February 2010
Canada606 Posts
October 07 2010 19:56 GMT
#12
>_<
C++ is such a terrible language to learn programming!

If you have time, pick up The C Programming Language. It's only 274 pages and you can read it in a week.

The above posters have already given good suggestions. For the math tutor question you want to use a for loop.
TL Android App Open Source http://www.teamliquid.net/forum/viewmessage.php?topic_id=265090
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 07 2010 20:05 GMT
#13
Thanks a lot, these are all very helpful, I knew TL would pull through. I know I'm not very practiced at this, and that's the exact problem (I believe I also said that in OP, but i digress).

Anyway, the syntax seems to be what's messing me up the most, so examples of the correct syntax are actually a lot more helpful than the literal code, since i'm positive that we won't be getting the same problems on the exam.

On October 08 2010 04:40 Adeny wrote:

// rectangle one:
if (area1 > area2);
{
cout << "The first rectangle is larger than the second one.\n";
}
else (area1 < area2);
{
cout << "The second rectangle is larger than the first one.\n";
}
return 0;



I tried fixing the syntax for this part, and I'm still getting a error message of 'else' without previous 'if.' Why is this?

On October 08 2010 04:40 Adeny wrote:
For the runners there are several methods, but I think your prof wants you to take a look at sorting algorithms, maybe? As an itroduction... There are very very many different ones. Maybe he just straight wants you to compare them, like so:


if (runner1 > runner 2 && runner1 > runner3)
{
runner 1 wins!
}



When we did a problem similar to this previously, we used stream compare, so I think this is just supposed to be building off of that.

On October 08 2010 04:40 Adeny wrote:
Or hell maybe he wants you to make a runner class... I doubt it though.

class Runner {
int time;
}

Runner jack;
jack.time = 10;


As for storing the names + times, you could use a 2d array.

int runners[name][time] = {
A, 1,
B, 2,
C, 3
};


You'll have a matrix looking like this

0,0 | 0,1
-----------
1,0 | 1,1
-----------
2,0 | 2,1

or

A | 1
-------
B | 2
-------
C | 3


I sure as shit hope this isn't what I'm supposed to do, because I've never seen anything like this before...


On October 08 2010 04:40 Adeny wrote:
The thing about "not negative values" either means you have to validate the input (i.e. check if it's a positive integer or not, for this you could use an ascii chart and check if each character in the input string is in the area you want, if that makes sense...) OR it could mean that the user will only input positive integers, in which case don't worry about it, and I assume that's what he means as these are beginner tasks.

Now, let's have a look at the loop one.
First off cin >> int is dangerous, but I think you shouln't worry about that now as in the above question the user will probably only input positive integers so let's just assume that (not good practice but w/e).

your loop should look something like this:

cin >> number;
int x = 0;
while (x < number)
{
x++;
} // this will loop until X = number

alternatively a more pretty loop would be

for (int x = 0; x < number; x++)
{
// do whatever here.
}


for loops are cool -

for ( variables; condition; increment/decrement )


these can be mixed and matched however you want, and you can leave some of them blank if you want, here's an infinite loop:

for (;;).


I'm 99% sure that he wants us to write the program so that if the user tries to enter a negative number, it will be invalid. The only way I can think of to do this that we have learned is to set up an if else statement that says if number is greater than zero, it will do the subsequent code, but if it's less than zero, it will display an error message.
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 07 2010 20:15 GMT
#14
These are the last problems. Updating OP.

Ocean Levels
*Assuming that the Oceans level is rising 1.5 millimeters per year, write a program that displays a table showing the number of millimeters that the Ocean will have risen each year for the next 25 years.

+ Show Spoiler [Code so Far] +
This looked really easy at first and I'm going through it right now, I'll post some code in a minute


The Greatest and Least of These
*Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all of the numbers have been entered, the program should display the largest and smallest numbers entered.
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
Scorcher2k
Profile Joined November 2009
United States802 Posts
October 07 2010 20:16 GMT
#15

// rectangle one:
if (area1 > area2);
{
cout << "The first rectangle is larger than the second one.\n";
}
else (area1 < area2);
{
cout << "The second rectangle is larger than the first one.\n";
}
return 0;

You shouldn't have semi colon after your if(area1>area2) or else(area1 < area2).
On October 08 2010 05:05 KiLL_ORdeR wrote:

I'm 99% sure that he wants us to write the program so that if the user tries to enter a negative number, it will be invalid. The only way I can think of to do this that we have learned is to set up an if else statement that says if number is greater than zero, it will do the subsequent code, but if it's less than zero, it will display an error message.

x=-1;
while (x<0){
cout<<"Please enter a positive number";
cin>>x;
}

Something like that should work.
Tenrou
Profile Joined March 2010
United States38 Posts
October 07 2010 20:21 GMT
#16
Please do not give OP codes to do his program. This is not helping him at all. OP is still having trouble with the syntax. I would suggest rereading the book and look at the examples in it.

Show nested quote +
On October 08 2010 04:40 Adeny wrote:

// rectangle one:
if (area1 > area2);
{
cout << "The first rectangle is larger than the second one.\n";
}
else (area1 < area2);
{
cout << "The second rectangle is larger than the first one.\n";
}
return 0;



I tried fixing the syntax for this part, and I'm still getting a error message of 'else' without previous 'if.' Why is this?


The compiler is expecting an "if" after that else because of the extra condition you addressed (area1 < area2).

You should also want to have a condition where area1 == area2.

If there are things that you have never seen (class, arrays, etc.), then do not worry about them. Your professor want you to do his assignment with the things you already know in class and through the assigned readings.
Marradron
Profile Blog Joined January 2009
Netherlands1586 Posts
October 07 2010 20:25 GMT
#17
On October 08 2010 04:56 TossFloss wrote:
>_<
C++ is such a terrible language to learn programming!

If you have time, pick up The C Programming Language. It's only 274 pages and you can read it in a week.

The above posters have already given good suggestions. For the math tutor question you want to use a for loop.


He's actually just learning C. Hardly anything he does is C++ related. Though I would recomend reading that C tutorial
Scorcher2k
Profile Joined November 2009
United States802 Posts
October 07 2010 20:32 GMT
#18
On October 08 2010 05:21 Tenrou wrote:
Please do not give OP codes to do his program. This is not helping him at all. OP is still having trouble with the syntax. I would suggest rereading the book and look at the examples in it.

Because examples don't give him code? I'm sorry but seeing code that works for problems I'm having or people pointing things out to me is the fastest way that I learn. Simply because you think that it might not help him does not mean that it is actually the case.
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
October 07 2010 20:37 GMT
#19
On October 08 2010 05:05 KiLL_ORdeR wrote:
Thanks a lot, these are all very helpful, I knew TL would pull through. I know I'm not very practiced at this, and that's the exact problem (I believe I also said that in OP, but i digress).

Anyway, the syntax seems to be what's messing me up the most, so examples of the correct syntax are actually a lot more helpful than the literal code, since i'm positive that we won't be getting the same problems on the exam.

Show nested quote +
On October 08 2010 04:40 Adeny wrote:

// rectangle one:
if (area1 > area2);
{
cout << "The first rectangle is larger than the second one.\n";
}
else (area1 < area2);
{
cout << "The second rectangle is larger than the first one.\n";
}
return 0;



I tried fixing the syntax for this part, and I'm still getting a error message of 'else' without previous 'if.' Why is this?

I'm sorry, let me try that again:

if (area1 > area2) // area 1 greater than area 2
{
cout << "blablah";
}
else if (area2 > area 1) // the else here is so that if the first if checks through as true, the elses will be ignored.
{
cout << "blahblah"
}
else // both areas are equal
{
cout << "blahblah"
}


Note that the if's shouldn't have semi colons.

As for the other ones this is becoming quite the clusterfuck, hang on...
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
Last Edited: 2010-10-07 21:43:39
October 07 2010 21:33 GMT
#20
This works fine...

int x = 0;
cin >> x;
if (cin.good() > 0)
{
cout << "user input is: " << x << endl;
}
else
{
cout << "user input is bad" << endl;
}


LOLOL DISREGARD THIS ENTIRE MESSAGE

+ Show Spoiler +
Ok, let's validate the input so that only digits between 0 and 9 will be accepted. If you use cin >> on an integer, your program will blow up if someone starts typing anything but strictly numbers. Because of that we have to jump hoops...

HUH, DISREGARD THIS LOL. It seems if you cin >> to an int, with characters and nonsense, the int stays 0... God damnit it.
+ Show Spoiler +

#include <string>
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
cout << "Input number or w/e\n";
string input;
cin >> input;
for (int x = 0; x < input.size(); x++)
{
if ( input[x] < 48 && input[x] > 57 )
{
cout << "Only 0-9";
break;
}
}

int validated = atoi(input.c_str());
if (validated > 0)
{
cout << validated;
}
else
{
cout << "Number must be over 0\n";
}

getch();
return 0;
}


What it does is take the users input, places it in to a string. Now it dissects the string, and checks each character seperately if its ASCII value is above or below 48-57, which is 0-9 on an ASCII table (ASCII Chart). Then convers the string to an integer using atoi(), and finally checks if the ints value is above 0.

Chances are though, your professor doesn't expect that of you and just poorly worded the assignment, maybe he wants you to assume that a user will always input numbers, in which case simply doing the following should work:

+ Show Spoiler +

int input;
cin >> input;
if (input > 0)
{
// do whatever here
}
else
{
// tell the user his input was bad.
}


Also god damn conversions in C++, jeez.
just_nick
Profile Joined August 2009
Canada35 Posts
Last Edited: 2010-10-07 22:27:36
October 07 2010 22:24 GMT
#21
Hey,

Try this:


if (area1 > area2) // area 1 greater than area 2
{
cout << "blablah";
}
else
{
// the else here is so that if the first if checksthrough as true, the elses will be ignored.
if (area2 > area1)
{
cout << "blahblah";
}
else // both areas are equal
{
cout << "blahblah";
}
}


Should work with no problems, for each "if" your allowed one else statement in C++
HowitZer
Profile Joined February 2003
United States1610 Posts
Last Edited: 2010-10-07 23:21:31
October 07 2010 23:17 GMT
#22
On October 08 2010 05:15 KiLL_ORdeR wrote:
These are the last problems. Updating OP.

The Greatest and Least of These
*Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all of the numbers have been entered, the program should display the largest and smallest numbers entered.


This will do the greatest and least. The getch at the end is to prevent the program from closing right away. You can change "int _tmain(int argc, _TCHAR* argv[])" to "int main()".


#include "stdafx.h"
#include <iostream>
#include <conio.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int nInputNumber = 0;
int nCounter = 0;
int anNumbers[100000];
int nMax = INT_MIN;
int nMin = INT_MAX;

cout << "This program will input a series of numbers and show the maximum and minimum\n";

cout << "Enter a number(-99 to finish): ";
cin >> nInputNumber;

while(nInputNumber != -99)
{
anNumbers[nCounter] = nInputNumber;
nCounter++;

cout << "Enter a number(-99 to finish): ";
cin >> nInputNumber;
}

for(int i = 0; i < nCounter; i++) {
int nNum = anNumbers[i];

if(nNum > nMax)
nMax = nNum;
if(nNum < nMin)
nMin = nNum;
}

if(nCounter == 0)
cout << "No numbers entered";
else
cout << "Maximum: " << nMax << endl << "Minimum: " << nMin;

cout << "\nEnter any key to quit . . .";

_getch();

return 0;
}
Human teleportation, molecular decimation, breakdown and reformation is inherently purging. It makes a man acute.
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 08 2010 00:15 GMT
#23
On October 08 2010 08:17 HowitZer wrote:
Show nested quote +
On October 08 2010 05:15 KiLL_ORdeR wrote:
These are the last problems. Updating OP.

The Greatest and Least of These
*Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all of the numbers have been entered, the program should display the largest and smallest numbers entered.


This will do the greatest and least. The getch at the end is to prevent the program from closing right away. You can change "int _tmain(int argc, _TCHAR* argv[])" to "int main()".


#include "stdafx.h"
#include <iostream>
#include <conio.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int nInputNumber = 0;
int nCounter = 0;
int anNumbers[100000];
int nMax = INT_MIN;
int nMin = INT_MAX;

cout << "This program will input a series of numbers and show the maximum and minimum\n";

cout << "Enter a number(-99 to finish): ";
cin >> nInputNumber;

while(nInputNumber != -99)
{
anNumbers[nCounter] = nInputNumber;
nCounter++;

cout << "Enter a number(-99 to finish): ";
cin >> nInputNumber;
}

for(int i = 0; i < nCounter; i++) {
int nNum = anNumbers[i];

if(nNum > nMax)
nMax = nNum;
if(nNum < nMin)
nMin = nNum;
}

if(nCounter == 0)
cout << "No numbers entered";
else
cout << "Maximum: " << nMax << endl << "Minimum: " << nMin;

cout << "\nEnter any key to quit . . .";

_getch();

return 0;
}


Thanks a lot. It's really helpful to look at the program done out like this. Since I know we won't have the exact same problems at the exam, it's really helpful to be able to see how these are structured.
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 08 2010 00:44 GMT
#24
I just did the oceans level one, but I fucked up somewhere.

+ Show Spoiler [Code so Far] +

#include <iostream>
using namespace std;

int main()

{
int years = 0;
cout << "Years Growth\n";
cout << "_____________________\n";
while (years <= 25)
{
cout << years << "\t\t" << (years + 1.5) <<endl;
years++;
}
return 0;
}

This one isn't doing what it's supposed to do. Instead of adding 1.5 each loop, it's instead starting at 1.5 and adding one. Gonna look back I think I just need to change years++
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
shadowryu
Profile Joined December 2007
United States12 Posts
October 08 2010 01:03 GMT
#25
I think you just need to change the (years + 1.5) to (years * 1.5) for it to work like you want. Putting the arithmetic into a cout stream isn't going to actually change the variable's value.
Disregard
Profile Blog Joined March 2007
China10252 Posts
October 08 2010 01:36 GMT
#26
Not contributing anything but I program in Java, some of it looks very similar.
"If I had to take a drug in order to be free, I'm screwed. Freedom exists in the mind, otherwise it doesn't exist."
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
October 08 2010 02:10 GMT
#27
On October 08 2010 09:44 KiLL_ORdeR wrote:
I just did the oceans level one, but I fucked up somewhere.

+ Show Spoiler [Code so Far] +

#include <iostream>
using namespace std;

int main()

{
int years = 0;
cout << "Years Growth\n";
cout << "_____________________\n";
while (years <= 25)
{
cout << years << "\t\t" << (years + 1.5) <<endl;
years++;
}
return 0;
}

This one isn't doing what it's supposed to do. Instead of adding 1.5 each loop, it's instead starting at 1.5 and adding one. Gonna look back I think I just need to change years++


Years * 1.5 instead of year + 1.5 should do it, but that's the messy way I'd probably do this

int years = 1;
float growth = 1,5;
while (years <= 25)
{
cout << "Year " << years << " - " << growth << " millimeters" << endl;
years++;
growth += 1.5;
}
Tenrou
Profile Joined March 2010
United States38 Posts
October 08 2010 03:03 GMT
#28
On October 08 2010 05:32 Scorcher2k wrote:
Show nested quote +
On October 08 2010 05:21 Tenrou wrote:
Please do not give OP codes to do his program. This is not helping him at all. OP is still having trouble with the syntax. I would suggest rereading the book and look at the examples in it.

Because examples don't give him code? I'm sorry but seeing code that works for problems I'm having or people pointing things out to me is the fastest way that I learn. Simply because you think that it might not help him does not mean that it is actually the case.


Programming is a creative process similar to creating a new art work. You CANNOT teach someone how to program. You can teach him the syntax and semantics within a program, but you cannot teach him how to program. He must learn how to use these tools creatively and create something useful. By giving him code that already does his programming assignment, you are starving him from knowing the whole process of how he should use those tools to create that program.


On October 08 2010 09:44 KiLL_ORdeR wrote:
I just did the oceans level one, but I fucked up somewhere.

+ Show Spoiler [Code so Far] +

#include <iostream>
using namespace std;

int main()

{
int years = 0;
cout << "Years Growth\n";
cout << "_____________________\n";
while (years <= 25)
{
cout << years << "\t\t" << (years + 1.5) <<endl;
years++;
}
return 0;
}

This one isn't doing what it's supposed to do. Instead of adding 1.5 each loop, it's instead starting at 1.5 and adding one. Gonna look back I think I just need to change years++


years is a variable of type int so it can only hold whole number.
+ Show Spoiler +

int years = 0;
years = years + 1.5; //years will become 1 because it truncates the decimal part away


years++ post increment the variable by 1 every time which is not what you want.
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 08 2010 03:20 GMT
#29
On October 08 2010 12:03 Tenrou wrote:
Show nested quote +
On October 08 2010 05:32 Scorcher2k wrote:
On October 08 2010 05:21 Tenrou wrote:
Please do not give OP codes to do his program. This is not helping him at all. OP is still having trouble with the syntax. I would suggest rereading the book and look at the examples in it.

Because examples don't give him code? I'm sorry but seeing code that works for problems I'm having or people pointing things out to me is the fastest way that I learn. Simply because you think that it might not help him does not mean that it is actually the case.


Programming is a creative process similar to creating a new art work. You CANNOT teach someone how to program. You can teach him the syntax and semantics within a program, but you cannot teach him how to program. He must learn how to use these tools creatively and create something useful. By giving him code that already does his programming assignment, you are starving him from knowing the whole process of how he should use those tools to create that program.


Show nested quote +
On October 08 2010 09:44 KiLL_ORdeR wrote:
I just did the oceans level one, but I fucked up somewhere.

+ Show Spoiler [Code so Far] +

#include <iostream>
using namespace std;

int main()

{
int years = 0;
cout << "Years Growth\n";
cout << "_____________________\n";
while (years <= 25)
{
cout << years << "\t\t" << (years + 1.5) <<endl;
years++;
}
return 0;
}

This one isn't doing what it's supposed to do. Instead of adding 1.5 each loop, it's instead starting at 1.5 and adding one. Gonna look back I think I just need to change years++


years is a variable of type int so it can only hold whole number.
+ Show Spoiler +

int years = 0;
years = years + 1.5; //years will become 1 because it truncates the decimal part away


years++ post increment the variable by 1 every time which is not what you want.


I agree with you about programming being similar to an art. I do understand how to develop a program in my head and I can look at a problem and understand the steps I need to take to solve it, but it's the syntax that is giving me trouble, since I've only written maybe 10 programs, focusing on a wide variety of things, and we're going at a pretty fast pace imo. It was weird, one day I started doing homework, and realized that I had no idea what was going on. when people post code, that's very helpful to me because I can look at how they write it, then go to Wascana and copy it in, and get a good grasp of all of the pieces.

for the second part, the growth needs to start at 0 at year 0, and increase by 1.5 each time the year increases by 1, which I think seems to be the opposite of what people are telling me to do.
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
Tenrou
Profile Joined March 2010
United States38 Posts
October 08 2010 03:29 GMT
#30
My advice is to read your book and every time you see something new, create a test program to use the new code. Check to see what it does and can't do.
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
October 08 2010 03:31 GMT
#31
for the second part, the growth needs to start at 0 at year 0, and increase by 1.5 each time the year increases by 1, which I think seems to be the opposite of what people are telling me to do.


Use the code I posted above but initialize the variables to 0 instead.
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 08 2010 07:21 GMT
#32
been doing some crazy serious work. I decided to go back to the basics and do all of the book problems, by chapter, until I have a good feel of all of the concepts, syntax, and types of problems. It's working really well and I wish I did this from the start, since now I pretty much have to stay up until I finish this, and it's currently 3:15 here

Here's the new code I wrote for the Math tutor program. I forgor to mention that we were supposed to includ a cin.getline code so that the "student" could press enter to view the answer.

+ Show Spoiler +

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main ()

{
unsigned seed = time (0);
srand(seed);
char ch;
int randa, randb, total;
randa = rand ()%50;
randb = rand ()%50;
total = randa+randb;

cout << " " << randa << endl;
cout << "+ " << randb << endl;
cout << "_____\n";
cout << "Press the [ENTER] key to see the right answer\n";
cin.get(ch);
cout << total << endl;

return 0;
}


So this will take two random numbers between 0 and 50, and then add them in the right format.


I'll update op with the others as I hit them. Thanks for all the help guys!
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 08 2010 13:50 GMT
#33
Finally got the area of rectangles one to work. Didn't stay up working all night, although I only got like 4 hours of sleep, and now I'm really tired.

+ Show Spoiler [Final Code] +

#include <iostream>
using namespace std;

int main()

{
int length, width, area1, area2;

// First Rectangle
cout << "What is the length of the first rectangle? ";
cin >> length;
cout << "What is the width of the first rectangle? ";
cin >> width;
area1 = length * width;
cout << "The area of the first rectangle is " << area1 << ".\n";

// Second Rectangle
cout << "What is the length of the second rectangle? ";
cin >> length;
cout << "What is the width of the second rectangle? ";
cin >> width;
area2 = length * width;
cout << "The area of the second rectangle is " << area2 << ".\n";

//Comparison
if (area1>area2){
cout << "The first triangle is larger\n";
}
else if (area1<area2){
cout << "The second rectangle is larger\n";
}
else if (area1==area2){
cout << "They are equal\n";
}

return 0;
}
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
carlt
Profile Joined October 2010
Germany3 Posts
October 08 2010 14:18 GMT
#34
Another helpful site to keep in mind is WolframAlpha, especially for any math problems you may have to do. For example you don't need to use a loop to add the numbers 1 to n.

Also, for the min and max numbers of a given series you can just compare the entered number to the current max / min number, there's no need to store all numbers.
Scorch
Profile Blog Joined March 2008
Austria3371 Posts
Last Edited: 2010-10-08 15:47:00
October 08 2010 15:35 GMT
#35
For the ocean level rising example, you want to use two variables: one for the level, and a second one for the loop. The loop variable describes the years and is incremented by 1 in each loop, until 25. The level increases by 1.5 in each loop.
You need a very exact approach to thinking for programming which feels unnatural and difficult at first. You need to figure out exactly what you want the program to do, step by step, and translate that into code.

For the last example, you may need a while(true) {...} loop, and when the input equals -99, you use the break; command to exit the loop. Just in case you didn't know about break. Or you use something like while(input != -99), which is the more elegant solution.
You see, there are often multiple ways to achieve the same goal. This is why some people call programming a creative process.
YiukeDukem
Profile Blog Joined June 2010
United States125 Posts
October 08 2010 17:44 GMT
#36
Typing on my phone right now, but here's the general idea of how you do it

Int years = 0
Double waterLevel = 0

While years < 25
years++
waterLevel = waterLevel + 1.5
Cout << years << " " << waterLevel << endl
quye
Slithe
Profile Blog Joined February 2007
United States985 Posts
October 08 2010 18:27 GMT
#37
I agree with some of the previous posters that we are giving away these answers too freely. We should let the student try and work through the problem on their own.
YiukeDukem
Profile Blog Joined June 2010
United States125 Posts
October 08 2010 19:47 GMT
#38
he's shown the initiative and i'd rather have someone show me exactly how to do it rather than lead me to it...idk probably just different methods of learning for some people
quye
Spazer
Profile Blog Joined March 2009
Canada8031 Posts
Last Edited: 2010-10-09 00:15:00
October 09 2010 00:11 GMT
#39
My god Wascana Eclipse is bloated. Dev C++ is 9MB compared to this 150MB monster.

Anyway, I thought I'd show you how to debug simple programs. I'm gonna use your ocean levels program as an example and go over your mistake in there at the same time.

+ Show Spoiler [Warning: really long] +
To begin with, your screen should look something like this:
[image loading]

Click on the text editor window (the window with all your code in it). Now go to Run > Debug As > Local C/C++ Application
[image loading]

This message box might come up. Choose yes to change perspectives.
[image loading]

Your screen should now look like this:
[image loading]
Here's an overview of the various important screens:
  1. This kinda tells you what the system's doing. Right now it's saying that the program is suspended at a breakpoint. I'll explain this in a minute. You can probably ignore this for the most part.
  2. This is the variables screen. It tells you about variables are used in the program as they are declared and changed.
  3. This is your program. Note the line I've circled, and how there's a tiny blue arrow on the left hand side. This means the program is currently stopped at that line.
  4. This is the console. It will show you the output of your program as it would normally appear in the command prompt. You've probably used this section before.


So here's what debug mode does: it stops your program at certain locations called breakpoints, and allows you to step through your program one line at a time. This way, you can observe the changes in your variables and locate any problems easier. Normally, you'd be able to set breakpoints wherever you'd like in your source file, but I can't figure out how to properly use this stupid program. Even the online help wasn't any use. -_-

When you enter debug mode using the steps I've described above, the breakpoint is automatically set at the first line of the program. Thus, your program is currently stopped at the line int years = 0;
Look at the variables window. Notice how years has shown up because it has been declared, but that the value is all screwed up. This is because the value has not been assigned to the variable.

Let's hit step into to advance the code one line:
[image loading]

[image loading]
Notice that the little blue arrow has gone down one line. Also notice that the variable years now has a value of 0.

I'm gonna keep going.
[image loading]
Now we're at the loop. Take a look at the variable screen. years is 0, which is less than or equal to 25, so we enter the loop.

Stepping further...
[image loading]
Look at the console and notice that we now have output. The reason why the first two cout statements didn't show up before this is that text is sometimes stored in the buffer instead of immediately being displayed. Suffice it to say that this is nothing to worry about.

Anyway, this is the part where your program screws up. This line:
cout << years << "\t\t" << (years + 1.5) <<endl;

Since years is 0, (years +1.5) gives you an output of 1.5 instead of 0.
As others have mentioned in this thread, having (years * 1.5) would fix this.

Strictly speaking, the expression (years +1.5) is bad since type int isn't meant to contain decimal values. However, the program is smart enough to typecast the integer as a float or double to compensate for this.

Stepping some more...
[image loading]
years has now incremented, as you can see.
The while loop has also ended, so we're now reevaluating the condition right now. years is still under 25, so we'll end up entering the loop again.

Stepping more...
[image loading]
Here we see that the output for 1 year is 2.5 instead of 1.5
Again, using the expression (years * 1.5) would solve this problem, giving an output of 1.5

Hit resume (outlined in green) to make the program run to the end without further stoppages. Hit terminate (outlined in red) to make the program stop running completely (means no more stepping) at its current location.
[image loading]


So that's a basic overview of how to debug your programs. Using debug mode will give you a better understanding of what your program is doing at every step, and help you locate those nasty bugs. It's a really nice feature you should learn to use.

Edit: By the way, I really hate Wascana Eclipse. It's not very intuitive at all. Given a choice, I'd use another development environment, but you guys might not get a choice in that. =/
Liquipedia
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
October 10 2010 09:36 GMT
#40
Amazing guide, Eclipse looks about the same as MSVC as far as the debug features go, so this guide should translate well.
LastWish
Profile Blog Joined September 2004
2013 Posts
Last Edited: 2010-10-10 15:18:41
October 10 2010 15:15 GMT
#41
On October 08 2010 06:33 Adeny wrote:
This works fine...

int x = 0;
cin >> x;
if (cin.good() > 0)
{
cout << "user input is: " << x << endl;
}
else
{
cout << "user input is bad" << endl;
}


LOLOL DISREGARD THIS ENTIRE MESSAGE

+ Show Spoiler +
Ok, let's validate the input so that only digits between 0 and 9 will be accepted. If you use cin >> on an integer, your program will blow up if someone starts typing anything but strictly numbers. Because of that we have to jump hoops...

HUH, DISREGARD THIS LOL. It seems if you cin >> to an int, with characters and nonsense, the int stays 0... God damnit it.
+ Show Spoiler +

#include <string>
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
cout << "Input number or w/e\n";
string input;
cin >> input;
for (int x = 0; x < input.size(); x++)
{
if ( input[x] < 48 && input[x] > 57 )
{
cout << "Only 0-9";
break;
}
}

int validated = atoi(input.c_str());
if (validated > 0)
{
cout << validated;
}
else
{
cout << "Number must be over 0\n";
}

getch();
return 0;
}


What it does is take the users input, places it in to a string. Now it dissects the string, and checks each character seperately if its ASCII value is above or below 48-57, which is 0-9 on an ASCII table (ASCII Chart). Then convers the string to an integer using atoi(), and finally checks if the ints value is above 0.

Chances are though, your professor doesn't expect that of you and just poorly worded the assignment, maybe he wants you to assume that a user will always input numbers, in which case simply doing the following should work:

+ Show Spoiler +

int input;
cin >> input;
if (input > 0)
{
// do whatever here
}
else
{
// tell the user his input was bad.
}


Also god damn conversions in C++, jeez.


Seems to me you need some help aswell.

You can use :

if(cin.fail()){
// print bad stuff
return -1;
}

Alternatively you can set cin.exceptions(istream::failbit) and catch istream::failure exception.


if (input[x] < 48 && input[x] > 57 )

You don't have to use 48 or 57 but :

if (input[x] < '0' && input[x] > '9' )

does the same.

Edit : Oh ok, you have edited the former message..
- It's all just treason - They bring me down with their lies - Don't know the reason - My life is fire and ice -
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
October 10 2010 16:52 GMT
#42
^Yeah, it's been a while since I C++'d, the manual method is probably from C I dunno, lately trying to learn C# has left my head spinning, too many C's.
KiLL_ORdeR
Profile Blog Joined June 2009
United States1518 Posts
October 10 2010 17:02 GMT
#43
On October 09 2010 09:11 Spazer wrote:
My god Wascana Eclipse is bloated. Dev C++ is 9MB compared to this 150MB monster.

Anyway, I thought I'd show you how to debug simple programs. I'm gonna use your ocean levels program as an example and go over your mistake in there at the same time.

+ Show Spoiler [Warning: really long] +
To begin with, your screen should look something like this:
[image loading]

Click on the text editor window (the window with all your code in it). Now go to Run > Debug As > Local C/C++ Application
[image loading]

This message box might come up. Choose yes to change perspectives.
[image loading]

Your screen should now look like this:
[image loading]
Here's an overview of the various important screens:
  1. This kinda tells you what the system's doing. Right now it's saying that the program is suspended at a breakpoint. I'll explain this in a minute. You can probably ignore this for the most part.
  2. This is the variables screen. It tells you about variables are used in the program as they are declared and changed.
  3. This is your program. Note the line I've circled, and how there's a tiny blue arrow on the left hand side. This means the program is currently stopped at that line.
  4. This is the console. It will show you the output of your program as it would normally appear in the command prompt. You've probably used this section before.


So here's what debug mode does: it stops your program at certain locations called breakpoints, and allows you to step through your program one line at a time. This way, you can observe the changes in your variables and locate any problems easier. Normally, you'd be able to set breakpoints wherever you'd like in your source file, but I can't figure out how to properly use this stupid program. Even the online help wasn't any use. -_-

When you enter debug mode using the steps I've described above, the breakpoint is automatically set at the first line of the program. Thus, your program is currently stopped at the line int years = 0;
Look at the variables window. Notice how years has shown up because it has been declared, but that the value is all screwed up. This is because the value has not been assigned to the variable.

Let's hit step into to advance the code one line:
[image loading]

[image loading]
Notice that the little blue arrow has gone down one line. Also notice that the variable years now has a value of 0.

I'm gonna keep going.
[image loading]
Now we're at the loop. Take a look at the variable screen. years is 0, which is less than or equal to 25, so we enter the loop.

Stepping further...
[image loading]
Look at the console and notice that we now have output. The reason why the first two cout statements didn't show up before this is that text is sometimes stored in the buffer instead of immediately being displayed. Suffice it to say that this is nothing to worry about.

Anyway, this is the part where your program screws up. This line:
cout << years << "\t\t" << (years + 1.5) <<endl;

Since years is 0, (years +1.5) gives you an output of 1.5 instead of 0.
As others have mentioned in this thread, having (years * 1.5) would fix this.

Strictly speaking, the expression (years +1.5) is bad since type int isn't meant to contain decimal values. However, the program is smart enough to typecast the integer as a float or double to compensate for this.

Stepping some more...
[image loading]
years has now incremented, as you can see.
The while loop has also ended, so we're now reevaluating the condition right now. years is still under 25, so we'll end up entering the loop again.

Stepping more...
[image loading]
Here we see that the output for 1 year is 2.5 instead of 1.5
Again, using the expression (years * 1.5) would solve this problem, giving an output of 1.5

Hit resume (outlined in green) to make the program run to the end without further stoppages. Hit terminate (outlined in red) to make the program stop running completely (means no more stepping) at its current location.
[image loading]


So that's a basic overview of how to debug your programs. Using debug mode will give you a better understanding of what your program is doing at every step, and help you locate those nasty bugs. It's a really nice feature you should learn to use.

Edit: By the way, I really hate Wascana Eclipse. It's not very intuitive at all. Given a choice, I'd use another development environment, but you guys might not get a choice in that. =/


Wow man, just wow.

We went over the debugging process for about half of one 50 minute class period, and haven't touched it since. This is really, really informative though, i'm really glad that you went through the effort of doing this, thank you very much.

We don't get a choice of which program to use. There is a list of programs we can use on the course webpage, but most of them cost money, and Wascana is free, and what we use in class
In order to move forward, we must rid ourselves of that which holds us back. Check out my stream and give me tips! twitch.tv/intotheskyy
Spazer
Profile Blog Joined March 2009
Canada8031 Posts
October 10 2010 17:19 GMT
#44
On October 11 2010 02:02 KiLL_ORdeR wrote:
Show nested quote +
On October 09 2010 09:11 Spazer wrote:
My god Wascana Eclipse is bloated. Dev C++ is 9MB compared to this 150MB monster.

Anyway, I thought I'd show you how to debug simple programs. I'm gonna use your ocean levels program as an example and go over your mistake in there at the same time.

+ Show Spoiler [Warning: really long] +
To begin with, your screen should look something like this:
[image loading]

Click on the text editor window (the window with all your code in it). Now go to Run > Debug As > Local C/C++ Application
[image loading]

This message box might come up. Choose yes to change perspectives.
[image loading]

Your screen should now look like this:
[image loading]
Here's an overview of the various important screens:
  1. This kinda tells you what the system's doing. Right now it's saying that the program is suspended at a breakpoint. I'll explain this in a minute. You can probably ignore this for the most part.
  2. This is the variables screen. It tells you about variables are used in the program as they are declared and changed.
  3. This is your program. Note the line I've circled, and how there's a tiny blue arrow on the left hand side. This means the program is currently stopped at that line.
  4. This is the console. It will show you the output of your program as it would normally appear in the command prompt. You've probably used this section before.


So here's what debug mode does: it stops your program at certain locations called breakpoints, and allows you to step through your program one line at a time. This way, you can observe the changes in your variables and locate any problems easier. Normally, you'd be able to set breakpoints wherever you'd like in your source file, but I can't figure out how to properly use this stupid program. Even the online help wasn't any use. -_-

When you enter debug mode using the steps I've described above, the breakpoint is automatically set at the first line of the program. Thus, your program is currently stopped at the line int years = 0;
Look at the variables window. Notice how years has shown up because it has been declared, but that the value is all screwed up. This is because the value has not been assigned to the variable.

Let's hit step into to advance the code one line:
[image loading]

[image loading]
Notice that the little blue arrow has gone down one line. Also notice that the variable years now has a value of 0.

I'm gonna keep going.
[image loading]
Now we're at the loop. Take a look at the variable screen. years is 0, which is less than or equal to 25, so we enter the loop.

Stepping further...
[image loading]
Look at the console and notice that we now have output. The reason why the first two cout statements didn't show up before this is that text is sometimes stored in the buffer instead of immediately being displayed. Suffice it to say that this is nothing to worry about.

Anyway, this is the part where your program screws up. This line:
cout << years << "\t\t" << (years + 1.5) <<endl;

Since years is 0, (years +1.5) gives you an output of 1.5 instead of 0.
As others have mentioned in this thread, having (years * 1.5) would fix this.

Strictly speaking, the expression (years +1.5) is bad since type int isn't meant to contain decimal values. However, the program is smart enough to typecast the integer as a float or double to compensate for this.

Stepping some more...
[image loading]
years has now incremented, as you can see.
The while loop has also ended, so we're now reevaluating the condition right now. years is still under 25, so we'll end up entering the loop again.

Stepping more...
[image loading]
Here we see that the output for 1 year is 2.5 instead of 1.5
Again, using the expression (years * 1.5) would solve this problem, giving an output of 1.5

Hit resume (outlined in green) to make the program run to the end without further stoppages. Hit terminate (outlined in red) to make the program stop running completely (means no more stepping) at its current location.
[image loading]


So that's a basic overview of how to debug your programs. Using debug mode will give you a better understanding of what your program is doing at every step, and help you locate those nasty bugs. It's a really nice feature you should learn to use.

Edit: By the way, I really hate Wascana Eclipse. It's not very intuitive at all. Given a choice, I'd use another development environment, but you guys might not get a choice in that. =/


Wow man, just wow.

We went over the debugging process for about half of one 50 minute class period, and haven't touched it since. This is really, really informative though, i'm really glad that you went through the effort of doing this, thank you very much.

We don't get a choice of which program to use. There is a list of programs we can use on the course webpage, but most of them cost money, and Wascana is free, and what we use in class

For whatever reason, programming classes usually don't teach you how to use the debugging features. I don't know why - it's just so useful. Debugging tells you so much about how your program operates that I don't know how I got by without it before. Anyway, enjoy.
Liquipedia
TossFloss *
Profile Blog Joined February 2010
Canada606 Posts
October 12 2010 05:29 GMT
#45
On October 08 2010 12:29 Tenrou wrote:
My advice is to read your book and every time you see something new, create a test program to use the new code. Check to see what it does and can't do.


Most textbooks are trash. You should read a book but make sure it's a good one.
TL Android App Open Source http://www.teamliquid.net/forum/viewmessage.php?topic_id=265090
Normal
Please log in or register to reply.
Live Events Refresh
Replay Cast
00:00
SEL S2 Championship: Ro16
CranKy Ducklings129
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
SpeCial 184
RuFF_SC2 123
ProTech119
CosmosSc2 30
Nina 3
StarCraft: Brood War
Artosis 801
NaDa 72
Aegong 52
Purpose 26
Dota 2
NeuroSwarm102
League of Legends
JimRising 343
Counter-Strike
fl0m1753
Other Games
summit1g11628
shahzam1017
Day[9].tv850
C9.Mang0477
ViBE197
WinterStarcraft137
Mew2King38
ROOTCatZ14
Vindicta6
Organizations
Other Games
BasetradeTV40
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 14 non-featured ]
StarCraft 2
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• iopq 1
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• masondota22109
League of Legends
• Doublelift4319
Other Games
• Day9tv850
Upcoming Events
LiuLi Cup
9h 15m
MaxPax vs TriGGeR
ByuN vs herO
Cure vs Rogue
Classic vs HeRoMaRinE
Cosmonarchy
14h 15m
OyAji vs Sziky
Sziky vs WolFix
WolFix vs OyAji
Big Brain Bouts
14h 15m
Iba vs GgMaChine
TriGGeR vs Bunny
Reynor vs Classic
Serral vs Clem
BSL Team Wars
17h 15m
Team Hawk vs Team Dewalt
BSL Team Wars
17h 15m
Team Hawk vs Team Bonyth
Code For Giants Cup
20h 45m
SC Evo League
1d 10h
TaeJa vs Cure
Rogue vs threepoint
ByuN vs Creator
MaNa vs Classic
Maestros of the Game
1d 14h
ShoWTimE vs Cham
GuMiho vs Ryung
Zoun vs Spirit
Rogue vs MaNa
[BSL 2025] Weekly
1d 16h
SC Evo League
2 days
[ Show More ]
Maestros of the Game
2 days
SHIN vs Creator
Astrea vs Lambo
Bunny vs SKillous
HeRoMaRinE vs TriGGeR
BSL Team Wars
2 days
Team Bonyth vs Team Sziky
BSL Team Wars
2 days
Team Dewalt vs Team Sziky
Monday Night Weeklies
3 days
Replay Cast
3 days
Sparkling Tuna Cup
4 days
LiuLi Cup
5 days
Replay Cast
5 days
The PondCast
6 days
RSL Revival
6 days
Maru vs SHIN
MaNa vs MaxPax
Liquipedia Results

Completed

CSL Season 18: Qualifier 1
WardiTV Summer 2025
HCC Europe

Ongoing

Copa Latinoamericana 4
BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21 Qualifiers
ASL Season 20
Acropolis #4 - TS1
CSL Season 18: Qualifier 2
SEL Season 2 Championship
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
BLAST.tv Austin Major 2025

Upcoming

CSL 2025 AUTUMN (S18)
LASL Season 20
BSL Season 21
BSL 21 Team A
Chzzk MurlocKing SC1 vs SC2 Cup #2
RSL Revival: Season 2
Maestros of the Game
EC S1
Sisters' Call Cup
Skyesports Masters 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
MESA Nomadic Masters Fall
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Disclosure: This page contains affiliate marketing links that support TLnet.

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.