Simple tutorial for C++

twinbaby

Supremacy Member
Joined
Jul 8, 2014
Messages
5,470
Reaction score
1,534
Hi there,

I know that C++ is backward compatible with C.
How can I use getChar() equivalent in C?
Why the need to declare a namespace std in on the top of the header,otherwise there will be a "undeclared indentifier cout" error message

Download http://go.microsoft.com/?linkid=9709949 to download Visual Studio 2010

1) File->New->Project

Create a new project in directory: C:\Users\Lenovo\Desktop\new\test\Debug\test.exe

2) Application Settings->Console Applications->New Project

3) Source File->New Item->test.cpp

On Test.Cpp

#include <stdio.h>
#include <iostream>
using namespace std;

int main(int argv){
cout << "Hello World" << endl;
cout << "Press any key and hit enter to continue" << endl;
getchar();
return 0;
}

Press Build 'F7' to Build Project

Press 'F5' to run the Project

When I type cin, i don't really know whats wrong,what is the package to import,is a way 2010 will hint you the package to declare like eclipse for java.

The thing is I was typing include on top of the list

How can I use "#include<" -> Selection List to find the include for the reading file.

It isn't as convenient as using eclipse.

Thanks.
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
Hi there,

I know that C++ is backward compatible with C.
How can I use getChar() equivalent in C?
Why the need to declare a namespace std in on the top of the header,otherwise there will be a "undeclared indentifier cout" error message



When I type cin, i don't really know whats wrong,what is the package to import,is a way 2010 will hint you the package to declare like eclipse for java.

The thing is I was typing include on top of the list

How can I use "#include<" -> Selection List to find the include for the reading file.

It isn't as convenient as using eclipse.

Thanks.


First of C++ is not a superset of C, as such we don't call it backward compatible. There are C syntax that will not compile using the C++ compiler. Objective-C, however, is a superset of C. I will leave this as an exercise for you.


C++ is namespace enabled, as such, it is possible to have cout and cin in a totally different namespace, such as abc::cin, or def::cout


There is no assumed namespace in C++. You need to declare it. I believe if any symbols that you are using cannot be unambiguously resolved to an absolute namespace, the compiler will throw errors.


cin and cout are iostreams objects defined in the iostream library. One place to refer to is Reference - C++ Reference


You guys have to learn to be less dependent on IDE to do programming. IDE is suppose to make you more productive, not become a slave of it. Read here c++ - Is there a shortcut to automatically include a class in visual studio 2010? - Stack Overflow
 

twinbaby

Supremacy Member
Joined
Jul 8, 2014
Messages
5,470
Reaction score
1,534
Hi,

I have got to declare using namespace std first.

Then I have got to use std:: -> (display a list of function) for std.

I just want to do File *f =

I need to type std::->(generate function)->fopen() and delete std again.
So troublesome.

Furthermore, for C++ i need to put File * f, this asterisk,unlike java I can just ignore the *.
 
Last edited:

twinbaby

Supremacy Member
Joined
Jul 8, 2014
Messages
5,470
Reaction score
1,534
reading file

FILE *f = fopen("test.txt","r"); // why the need for an * again i recall in java only need to File f = new File("test.txt");
while(fgets(line,80,f) != NULL){ // in java NULL or null doesn't matter
printf("%s",line);//in java I can use System.out.println(""); is there a shorter way to print out the line
}
 

twinbaby

Supremacy Member
Joined
Jul 8, 2014
Messages
5,470
Reaction score
1,534
Ok,to take on any programming assignment,we need to know at the how to do this.Anything missing please advice.

  1. Write a Hello World
  2. Create a Loop
  3. Display item(s) in an array
  4. Read a .txt file
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
Hi,

I have got to declare using namespace std first.

Then I have got to use std:: -> (display a list of function) for std.

I just want to do File *f =

I need to type std::->(generate function)->fopen() and delete std again.
So troublesome.

Furthermore, for C++ i need to put File * f, this asterisk,unlike java I can just ignore the *.

FILE *f = fopen("test.txt","r"); // why the need for an * again i recall in java only need to File f = new File("test.txt");
while(fgets(line,80,f) != NULL){ // in java NULL or null doesn't matter
printf("%s",line);//in java I can use System.out.println(""); is there a shorter way to print out the line
}

Ok,to take on any programming assignment,we need to know at the how to do this.Anything missing please advice.

  1. Write a Hello World
  2. Create a Loop
  3. Display item(s) in an array
  4. Read a .txt file

Dear twinbaby,

if you find certain things at this novice level "troublesome" and "inconvenient", I highly recommend that you drop your pursue on Computer Science. Clearly Computer Science is not going to be simple and hence words like "troublesome" and "inconvenient" contradicts with the fundamental spirit of Computer Science. Computer Science is to make things possible, and making things possible doesn't necessarily has to be "simple" and "convenient".

I hope you get this hardcoded into your mindset, change your attitude looking at technology and then decide if you want to continue pursue on this matter ? Is that alright ?

First of all, I would like you to discard on Java and learn C++ the way it was meant to be. The general concepts of computing can be retained, but empty your cup on what Java has taught you and learnt C++ from its fundamental. Just like how English is different from Mandarin, we don't complain that English only has 26 alphabets and words are made out of them, while Mandarin comes in strokes but with over tens of thousands of different characters. It's how these 2 programming languages differs. If you think an extra '*' confuse you, you have not seen the real thing at all. Start into C++ STL and you will see even more quirkiness in language itself.

First of all, Java only has Reference construct, it does not offers Pointer construct. Pointers are more powerful than just References. C++ has both Pointers and References. However even so, References in C++ are declared using '&', Eg: int x; int& y = x;

If you want to skip what I am going to say from this point onwards, please go pick up a C++ Beginners book from the nearest National Library, such as Amazon.com: Ivor Horton's Beginning ANSI C++: The Complete Language (Expert's Voice) (9781590592274): Ivor Horton: Books.
You will find no lacking of such books in the library since C++ has be around for a very long time. If anyone recommend you should start with C++11, forget that advice. What you need is fundamentals on C++.

Using namespace, C++ will not know which package does a symbol belongs to, if it is not declared in the same file or included. For included header files(also known as declaration files), a lot of them uses namespaces to separate their symbol from other libraries. The standard libraries in C++ own the "std" namespace. As such, standard tools like cin, cout and a lot more other such variables/objects, classes or functions are to be referred using std::* namespace.

For "File *f", f is a pointer variable. It store memory addresses and points to a type "File". In this case, type "File" is a structure.

Below is a simple example of how you can play with References and Pointers.

Code:
#include <iostream>

using namespace std;

int main(int argv, char** argc) {
  int i;
  FILE *f = NULL;
  f = fopen("my.txt", "r");
  FILE& rf = *f;
  char s[1024];
  fgets(s, 100, &rf);
  printf("%p %s", f, s);
  fclose(f);
  return 0;
}

Those methods of reading file using fgets, open a file using fopen are not exactly part of C++. They are established in C language. C++ has its own way of manipulating I/O. Please read up Input/output with files - C++ Tutorials

Who set you the standard of what you should know in order to complete C++ assignments ? You might want to refer to the tutor or institute that is setting you such standards based on their syllabus. My standard of what a C++ programmer should know is a far longer list that what you have provided.
 

twinbaby

Supremacy Member
Joined
Jul 8, 2014
Messages
5,470
Reaction score
1,534
To some extent I agree on your first para,some time I work doesn't matter what the content is but how your re-phrase put across your words,so that others will help you.

So you mean * is like a way to store a permanent address to change the content of the variable.
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302

ykgoh

Master Member
Joined
Jan 1, 2000
Messages
2,782
Reaction score
0
There are several issues and grouses raised by TS.

  • Differences in programming language syntax.
  • Differences in IDE behaviour.

Won't say they're invalid. Some people are more affected by them than others.

If TS is in a polytechnic doing an IT diploma, perhaps you should seriously rethink your future career and further education. Perhaps not as a software programmer, but in other IT roles since programming seems to rankles you a lot. Or perhaps see if you should switch to other field for your bachelor degree programme.

IT and technology landscape is very fragmented and many technologies are inconsistent or incompatible with each other. Many tech vendors build their proprietary products to be incompatible with others, and usually promote an entire platform or ecosystem of products to you. If you cannot stomach such an messy industry environment and culture, seriously talk to some IT professionals or try out an internship/attachment with an IT company to experience how it's like and make a decision.

My blood pressure rose from 120 (as a fresh grad) to 150 in 5 years working in the IT field trying to piece things together while absorbing internal injuries from the office politics and finger pointing when projects fail. Nobody appreciates your overtime in the background while trying to make things work, and people only notice when things don't work. That's the reality of IT industry. It's a thankless job.
 

twinbaby

Supremacy Member
Joined
Jul 8, 2014
Messages
5,470
Reaction score
1,534
So from this example,I understand that ptr_p = &x is used to store the address of variable for x, *ptr_p deference x to get its address and change its value to 10.

#include<stdio.h>

int main()
{
int x;
int *ptr_p;

x = 5;
ptr_p = &x;

*ptr_p = 10;

printf("%d\n", x);

return 0;
}
 

twinbaby

Supremacy Member
Joined
Jul 8, 2014
Messages
5,470
Reaction score
1,534
Hi Ykgoh,

Please see my post previously on "Why don't be a programmer", I shared the same sentiment with you.

Why not be a programmer

Currently,in my company programmer double up as database adminstrator,which they have to travel through and fro from work to handle sensitive information.They often have to do the patch work assigned by a level 1 helpdesk.

In the past I have interned in a start up,I was facing a lot of pressure from my supervisor that I almost quarrel with him and such that he doesn't want to give me my allowance for that day,and the boss I worked with is very unhelpful.

I was interning in one large private company in Singapore,the intern there work for like overtime everyday,checking database violation and do the Java coding.

In school,I worked with some really stubborn programmer,I would actually do the portion which requires the select statement and I would ask him to do the portion which requires the insert
statement,during the day of the presentation,my portion with the display data/generate report module got nothing to show.

There are many people in my polytechnic,I asked them if they want to do coding next time they say no,they also choose courses like ASP.NET instead of J2EE programming module.

However,5 years down the road,I saw them taking degree like Computer Science and Engineer Major,and having job titles like 'Senior Content Engineer' & 'IT security Analyst'.

I see some of their profiles for my Uni Cohort - putting skills like C++, Java, PHP, Xampp, it is obvious for computing graduate the mostly like career path is to be a software engineer. Nowadays,with the influx of FT,who can work longer,better,faster. Singaporean not only have to compete with Singaporean but also FT.

I have heard friend who quarrelled with their supervisor to the extend quitting the organization.

I have once interviewed someone,they said they have went 48 hours without a single day of sleep,all because of some software crisis with some fields in the database causes the order number to be wrong.

The supervisor will force him to meet the demand,if he can't he will be forced to stay back overtime without additional allowance.

I told my prospective employer that I see programming as a value-added not a must for me to do. Currently,I am the odd one out doing a technical analyst role which is customer facing job,I feel less pressure compared to many of peers doing programming job.
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
So from this example,I understand that ptr_p = &x is used to store the address of variable for x, *ptr_p deference x to get its address and change its value to 10.

Code:
#include <stdio.h>

int main() {
  int x;
  int *ptr_p;

  x = 5;
  ptr_p = &x;

  *ptr_p = 10;

  printf("%d\n", x);

  return 0;
}

Minor correction to *ptr_p deference x.

*ptr_p dereference the memory address stored in ptr_p, "x" is not in the topic. ptr_p can store any memory address even 0, however, if your program has no privilege to access that particular part of the memory, then it will likely be a segmentation fault or bus fault.

It is only deliberately that ptr_p store the same memory address as variable x, but when you want to fully understand pointers, you have to be very concise with what you are dealing with.

*ptr_p = 10 is an assignment statement to store the value of 10 to the memory address pointed by ptr_p, and the way to store that value is using an integer type, since ptr_p is declared as an integer pointer. If ptr_p is declared as a different type, such as a floating point type or a long integer or unsigned integer type, the result will be different.


Update: A simple example to show you the feature of using proper Type with Pointers
Code:
#include <stdio.h>

int main() {
  int x = 0;
  char *ptr_p = (char*)&x;

  *ptr_p = 'A';

  printf("%d\n", x);

  return 0;
}

The printed output will be 65, 65 is the ASCII value of 'A'

I must also highlight that the reason why it is 65 is not a miracle. That's because I ran my codes in a system architecture of Little Endian(e.g.: Intel). If it is of Big Endian(e.g.: PowerPC), the answer will not be 65 but (65<<8)=16640
So you can see how low level C and C++ goes. What you do matters on which architecture you are operating on.

Apple uses PowerPC Motorola processors previously and now Intel processors. (That's how confusing things can be)
So don't be mistaken by how much Java has did for programmers nowadays. So many are shield from all these details.
Formal Endianness information can be found at http://en.wikipedia.org/wiki/Endianness
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
Hi Ykgoh,

Please see my post previously on "Why don't be a programmer", I shared the same sentiment with you.

Your post on this topic has been demystified. Please stop using it as a valid reason for not to be a programmer, because much of the situation as you have depicted in that post, I have already highlighted that they are found in any other industries, not just limited to the IT industry.

If that is the reason why one shouldn't be a programmer, I'm sure you wouldn't find any other work interesting either if you encounter these situations in any other industries.
 
Last edited:

ykgoh

Master Member
Joined
Jan 1, 2000
Messages
2,782
Reaction score
0
Your post on this topic has been demystified. Please stop using it as a valid reason for not to be a programmer, because much of the situation as you have depicted in that post, I have already highlighted that they are found in any other industries, not just limited to the IT industry.

If that is the reason why one shouldn't be a programmer, I'm sure you wouldn't find any other work interesting either if you encounter these situations in any other industries.

Chill man. At least TS realizes early he/she hates programming, and probably not suited for the IT industry, or at least as a programmer. Find something else that appeals more to him/her bah.

Anyway, is this what TS wants to know? How to read a character from cin in C++?

Read a character from keyboard : cin « Development « C++ Tutorial

The thread seems to divert away from the first post about I/O to a refresher lesson on C pointers and C++ references? And then I lose track of whether TS is asking about C++ or C. :s11:

As for Visual Studio being less user-friendly than Eclipse, either feedback to Microsoft or use Eclipse CDT for C++ programming? :)
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
Chill man. At least TS realizes early he/she hates programming, and probably not suited for the IT industry, or at least as a programmer. Find something else that appeals more to him/her bah.

Anyway, is this what TS wants to know? How to read a character from cin in C++?

Read a character from keyboard : cin*«*Development*«*C++ Tutorial

The thread seems to divert away from the first post about I/O to a refresher lesson on C pointers and C++ references? And then I lose track of whether TS is asking about C++ or C. :s11:

As for Visual Studio being less user-friendly than Eclipse, either feedback to Microsoft or use Eclipse CDT for C++ programming? :)

I'm actually quite chilled. It's not the first time I have come across such kind of post and I wouldn't expect it to be the last either :) I'm very direct in my way of response at times, I don't like to waste time on some topics which in the first place should be something one ponder over oneself.

I would like to often put these kind of statements down mainly because more often than not, it's crybaby behaviour and clearly this industry doesn't need much of such nonsense and should be concentrating on building it up along with the process of building oneself up at the same time.

Clearly I was expecting it to be more technical in this thread than to be otherwise, however the thread started with a tint of "unwillingness" using keywords like "troublesome" and so forth. If I'm the supervisor of TS to have heard such kind of sentiments in my workplace, I would have ask TS to pack up immediately and stop wasting anybody's time.

However, since the thread contains technical enquiries and TS did continue to enquire, as such I will answer them to my capacity.
 

ykgoh

Master Member
Joined
Jan 1, 2000
Messages
2,782
Reaction score
0
Anyway to TS, if you're doing C++, try to avoid using those C library functions.

In C++, those stdio.h functions are largely replaced by iostream which does the same thing. Although the compiler won't penalize you or even complain about your use of C functions, I recommend you not to mix them for code maintainability and clarity if you can. Imagine you or another programmer takes over a C/C++ spaghetti "masterpiece"? I always get a bad migraine when I see "transvestite" codes.

I guess C functions are allowed in C++ to maintain backward compatibility with legacy C codes which programmers have no time to rewrite/port to C++.

For a new C++ project, go pure C++ all the way. Forget the FILE* and fopen, and use ifstream and ofstream.
 

twinbaby

Supremacy Member
Joined
Jul 8, 2014
Messages
5,470
Reaction score
1,534
When I use Java I can do by java.util.->(selection list)->Scanner,even eclipse can show some hint(dialog) on what the class is suppose to do.

I thought you say iostream so I tried iostream->(selection list),then when I tried std::ifstream then it shows out.

I current have VS 2013 installed in computer,will it work better,any big change the past 3 years? In the past when I started learning Java, I learn from using JCreator, then NetBeans, then I slowly pick up how to go to do command line by using Computer->Properties->Advance->Enviroment to change the file path to match the latest java jdk.

Its not like I don't know bcc(borland) to compile code,just not use to it yet.
 
Last edited:

ykgoh

Master Member
Joined
Jan 1, 2000
Messages
2,782
Reaction score
0
Hi there,

I know that C++ is backward compatible with C.
How can I use getChar() equivalent in C?

Use the get method in istream. e.g cin.get();

Why the need to declare a namespace std in on the top of the header,otherwise there will be a "undeclared indentifier cout" error message

You do Java programming also import java.io package before you can System.out.println(), don't you? Same concept no?

cin (C++) = System.in (Java)
cout (C++) = System.out (Java)


When I type cin, i don't really know whats wrong,what is the package to import,is a way 2010 will hint you the package to declare like eclipse for java.

The thing is I was typing include on top of the list

How can I use "#include<" -> Selection List to find the include for the reading file.

It isn't as convenient as using eclipse.

Thanks.

Can't remember how Visual Studio behaves for C++ programming. I believe Eclipse builds up a hashmap of known functions, classes and methods from scanning the import libraries of JAR files and runtime and use them to suggest the proper import. It's like a convenient reverse lookup.

But the proper way is for the programmers to specify what to include in the project and then VS then reads the class structures to suggest methods later on (Intellisense auto-completion). Maybe Visual Studio doesn't do this. Can't be sure myself.
 

ykgoh

Master Member
Joined
Jan 1, 2000
Messages
2,782
Reaction score
0
-snip-
I current have VS 2013 installed in computer,will it work better,any big change the past 3 years?
-snip-

I don't think much change or improvement in the Intellisense auto-completion for C++. Microsoft most probably updated the IDE/SDK to support application development for Windows 8 Metro/Modern interface and whatever new features in newer Windows only.

The C++ that we're touching is still the same basic core things that have not changed. Kind of like whether Java System.out.println has changed from Java 1.4, 5, 6 or 7? Well, afaik it hasn't changed a single bit at all.
 
Important Forum Advisory Note
This forum is moderated by volunteer moderators who will react only to members' feedback on posts. Moderators are not employees or representatives of HWZ Forums. Forum members and moderators are responsible for their own posts. Please refer to our Community Guidelines and Standards and Terms and Conditions for more information.
Top