Curly bracket problem

Hi everyone,


I've just got a job as a computer teacher and need to teach C++. I did Fortran and Basic many years back.

I am trying to do basic input/output and found this program below, which I tried to adapt to my Microsoft 2010 Express Compiler.

Unfortunately it doesn't like the curly brackets......

Any suggestions please?

Many thanks

Graham

#include "stdafx.h"
#include <iostream>
using namespace std ;

// enter the temperature in Celsius
int celsius () ;
{

cout << “Enter the temperature in Celsius:”;
cin >> celsius ;
}
// calculate conversion factor for Celsius
// to Fahrenheit
int factor ();
{
factor = 212 - 32;
// use conversion factor to convert Celsius
// into Fahrenheit values}
}
int fahrenheit ();
{
fahrenheit = factor * celsius/100 + 32;
}
// output the results (followed by a NewLine)
{
cout << “Fahrenheit value is:”;
cout << fahrenheit << endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}
there are all sorts of problems with this, the scope of your variables is all wrong, you put semicolons after function definitions and then go on to write the function body, the way you convert to farenheit is wierd, why 212 - 32, rather than just 180? =S

A function should look like this

1
2
3
4
returnType functionName(argument list) // no semicolon here!
{
    // body of function
}


bear in mind that variables declared inside of a function are only in scope inside of that function, so what you do here

1
2
3
4
int fahrenheit (); // there shouldn't be a semicolon here
{
    fahrenheit = factor * celsius/100 + 32;
}


well firstly the variable farenheit doesn't exist, you never declared it anywhere, you declare a function named farenheit, and if you did declare a variable named farenheit inside of the function it wouldn't be available anywhere else.

To convert to farenheit from celsius you multiply the temperature in celsius and multiply by 1.8, then add 32. Here's an example of a function to do that, you'll have to incorporate it into your program.

1
2
3
4
5
float celsiusToFarenheit(float celsius) 
{
    float farenheit = (celsius * 1.8) - 32; // declares a variable named farenheit
    return farenheit; // send the result back to the place where the function was called
}


Also, please use code tags when posting code it makes it much easier to read.
Last edited on
You've got the syntax just fundamentally wrong.

This creates an int named celcius
int celsius;

This is declaring that a fuction named celcius exists, and that it returns an int, and that it takes in no parameters
int celsius ();

This is defining the complete function
1
2
3
4
5
6
int celsius ()
{

cout << “Enter the temperature in Celsius:”;
cin >> celsius ;
}


I think you should read: http://www.cplusplus.com/doc/tutorial/functions/

You've got no main function; the main function is where execution begins. Without one, it's just not a C++ program.

http://www.cplusplus.com/doc/tutorial/program_structure/

and consider just starting at the beginning:
http://www.cplusplus.com/doc/tutorial/
Last edited on
Alas, two response posts before I could completely formulate an answer...

C++ doesn't work like FORTRAN or BASIC -- it requires a definite syntactical structure. All code must be in a function, and you cannot nest functions.

If you take the time to read through the tutorials on this site (as Moschops linked for you) you will be up to speed, sufficient to teach basic C++, at least.


A couple of professional notes to help you get started.

--- 1 ---

Avoid teaching dangerous "simplified" constructs and stick with correct ones. It may require a bit more typing, but it has the same memetic value without the horrors. Then when you completely remove the scaffolding (after your course is completed) your students will not need to unlearn bad habits you shouldn't have modelled for them.

For example, you used a common bad beginner's idiom by recurring to system() to keep the console window open long enough to see the program's output on Windows. Don't do that. The system() command has very well-documented issues, not the least of which is that it subverts system security. Instead, insist that the student understand a basic piece of information about handling user input:

    All user input is terminated by pressing the ENTER key.

Then, as the student gathers input, he should get rid of the ENTER key presses (the 'newlines') at the end of each input. At the end of the program, he can then ask for, essentially, a blank input: press the ENTER key.

--- 2 ---

Keep program flow and I/O in the main() function. Delegate computation to other functions. Functions should not know anything about the world outside itself.

A simple function to ask for and get user input is not necessary -- as it is properly part of the main program. The 'celsius' function knows a little too much about the world -- it is trying to do something that belongs in main(): interact with the user and modify data outside itself.

Likewise, a function to calculate part of a formula is not necessary. Calculations should not be split up any more than absolutely necessary. The 'fahrenheit' function does not represent a complete formula, and it knows too much about things outside itself. (Remember, a function takes an argument and uses only that argument (or arguments) to compute a value to return to the caller.)

--- 3 ---

Stick to well-known formulae. The F-->C and C-->F functions are pretty standard fare:
http://www.albireo.ch/temperatureconverter/formula.htm
Also be careful how you space out your operations.

    factor * celsius/100 + 32

This is just too easy to read as (factor * (celsius/100)) + 32. Yet, because 'celsius' is an integer, the integer division would likely produce zero for normal temperatures, and the result would always be around 32. Remind students of their basic mathematical order of operations (PEMBAS or whatever weird acronym they are familiar with). It does not matter that the calculation would actually work, because what the student is learning is in part assumed by the way you present it. It would have been better to write:

    factor*celsius / 100 + 32

Best practice, IMHO, is to put equal spacing around all operators and, if necessary, apply liberal use of parentheses. Hence, the following are best:

    ((factor * celsius) / 100) + 32
    factor * celsius / 100 + 32


--- 4 ---

Make sure to point out compiler-specific stuff, such as the #include <stdafx.h> thing that Microsoft compilers like to have. If you think that your students may be using non-MS compilers (assume that some will!), then you may even have them wrap it up so that both you and they can compile cleanly:

1
2
3
#ifdef _MSC_VER
#include <stdafx.h>
#endif 

---------

Well, here is some code that explains itself pretty well. Feel free to use it as part of your coursework.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <limits>
using namespace std;

//-------------------------------------------------------------------
// This is our library function to get rid of the ENTER key after
// the user has given us input.
//
// (Remember, the user will ALWAYS press ENTER after EVERY input!)
//
void clear_enter_key()
  {
  cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
  }

//-------------------------------------------------------------------
// This is our library function to PAUSE the program.
//
void press_enter_to_continue()
  {
  cout << "Press ENTER to continue." << flush;
  clear_enter_key();
  }

//-------------------------------------------------------------------
// This function converts C to F using the well-known 
// formula:
//           9
//   F = C * - + 32
//           5
//
// It is important to remember that since we are using
// INTEGERS that 9/5 is ONE, so we rely upon operator
// precedence order to do things from left to right:
// first we multiply by 9, then integer divide by 5,
// then add 32.
//
// The results would be more precise if we were using
// 'float' instead of 'int', because that division would
// then be a floating-point division. Do you see why?
//
//   If C is an 'int', then C * 9 is an 'int'.
//   If C is a 'float', then C * 9 is a 'float'.
//
int celsius_to_fahrenheit( int C )
  {
  return C * 9 / 5 + 32;
  }

//-------------------------------------------------------------------
// This is the main program.
//
int main()
{
  int celsius;

  cout << "Enter the temperature in Celsius: ";
  cin >> celsius;
  clear_enter_key();

  int fahrenheit = celsius_to_fahrenheit( celsius );

  cout << "The temperature in Fahrenheit is " << fahrenheit << ".\n";

  press_enter_to_continue();
  return 0;
}

Once that is digested, it might be a workable exercise to have the students write a function to work the other way:

1
2
3
4
int fahrenheit_to_celsius( int F )
{
  return (F - 32) * 5 / 9;
}

Hope this helps.
Last edited on
Since you are an instructor, please allow me the indulgence of tossing out a little peeve of mine.
There are three sets of grouping characters in C and C++.
Parens () Marks list of arguments and sets precedence
Braces {} used for grouping
Brackets [] used in array indexing.

(note: list is not comprehensive)

I don't think you will ever see the tems curly brackets or square braces. That means prefixing "braces" with "curly" and prexfixing "brackets" with "square" has no significant meaning. In this context they are useless prefixes and should be dropped.

I suggest that we all use the terms "braces" and "brackets."


Pet peeves are often due to unwarranted belief that one's own way of thinking is more correct than others'.
http://en.wikipedia.org/wiki/Bracket
Duoas (5417)

Many thanks to you and the others for all the help and advice.

I'm still having problem with the definitions at the start for the compiler, could you suggest a solution please? This was from the code your kindly wrote for me.

Many thanks

Graham

1>------ Build started: Project: Temp conversion 2, Configuration: Debug Win32 ------
1> stdafx.cpp
1> Temp conversion 2.cpp
1>c:\users\graham\documents\visual studio 2010\projects\temp conversion 2\temp conversion 2.cpp(1): warning C4627: '#include <iostream>': skipped when looking for precompiled header use
1> Add directive to 'StdAfx.h' or rebuild precompiled header
1>c:\users\graham\documents\visual studio 2010\projects\temp conversion 2\temp conversion 2.cpp(2): warning C4627: '#include <limits>': skipped when looking for precompiled header use
1> Add directive to 'StdAfx.h' or rebuild precompiled header
1>c:\users\graham\documents\visual studio 2010\projects\temp conversion 2\temp conversion 2.cpp(68): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Last edited on
Open your project's properties

Go to Configuration Properties -> C/C++ -> Precompiled Headers

Change the option "Create/Use Precompiled Header" to "Not Using Precompiled Headers"

Click Apply. Close the project properties, and the next compile should succeed (maybe do a full rebuild to be safe).

That way, you won't have to include a "stdafx.h" in your project.

(those steps work for Visual Studio 2005, anyway. Don't know if any of the options have changed names in five years).

Also, see http://en.wikipedia.org/wiki/Precompiled_header ("stdafx.h" is described under Common Implementations)

1
2
// It is important to remember that since we are using
// INTEGERS that 9/5 is ZERO 

This should be ONE (not ZERO).

Wikipedia wrote:
{ } — curly brackets, definite brackets, swirly brackets, birdie brackets, Scottish brackets, squirrelly brackets, braces, gullwings, fancy brackets, or squiggly brackets

So calling these "squirrelly brackets" from now on.
Last edited on
Many thanks, all works :))
This should be ONE (not ZERO).

Yoinks! I'll fix that above!
{ } — curly brackets, definite brackets, swirly brackets, birdie brackets, Scottish brackets, squirrelly brackets, braces, gullwings, fancy brackets, or squiggly brackets


Pull out your copy of K&R, "The C Programming Language" First edition, the original. You still have that, ..., Right?

Page 6. They call those characters "braces" Given the K&R economy on everything to do with C, dispensing with useless adjectives such as "curly" and all the rest makes complete sense.
I'm sure I've read K&R more times than you.

Your reasoning is fallacious. K&R are authorities on C, not English.

It is not unreasonable for them to pick a lexicon and stick with it. It is, however, beyond their qualification to proclaim the only true names of the punctuation they use -- which, by the way, they have not done.

I assume that you have actually read the passage you referred to me, so I suggest you read it again. Ritchie was not telling us the absolute name of the braces {}, he was giving the reader a vocabulary with which to reference them. This is a surprisingly common practice in technical literature.


I don't disagree with using the vocabulary suggested by K&R when programming, but you go too far when you abuse others less endowed with original editions of K&R's The C Programming Language than us for simply using vocabulary common to English speakers around the world to refer to those funny things we use to bracket everything in C and C++.

Perhaps you could better put it something like:
K&R call those curly {} things braces and those square [] things brackets. Perhaps your students would benefit from learning them by those names also.
instead of the rude:
Your use of the language evidences FAIL and is littered with USELESS WORDS with NO SEMANTIC VALUE and you ought to do it like me.


The OP did nothing wrong by calling them "curly brackets". But you did when you told him his language was wrong.
Do we not take the ISO C standard as the definition of C now? Using K&R first edition as the definition of C seems like using Johnson's dictionary as the arbiter of spelling.
Duoas,
I wrote: "please allow me the indulgence." I did not abuse anyone. I said the words were incorrect, I said nothing about the poster.

Flame off guy. You are way overheated.
Topic archived. No new replies allowed.