::cout << 4 moves the value of 4 to the console
std::cin >> x moves the value from the console into x
(Admin note: Discussion of the std::namespace and using statements has been moved to lesson 1.8a -- Naming conflicts and the std namespace)
I don’t understand why main is set to be an integer int main
The return statement
hello sir
#include<iostream>
int main()
{
std:: cout << "hello world"; << "hello world";
return 0;
}
sir what is the problem when i like this
get rid of the semicolon (;) after
the first "hello world"
Hi!
Quick question
Is there any advantage of using std::endl over just "\n".
Thanks!
In most cases, no. I talk about this topic more in lesson 2.7.
Whenever I run the code through VS2015, it just runs the program but nothing pops up or prompts me like it used to… did I mess up something and can I fix it?
Are you actually running the program, or just compiling it without running it?
Oh lemme see if thats what is happening
Yup… wasnt running the actual program smh
Hey Alex,
what’s the difference between the use of :
std::cout << "You entered " << x << std::endl;
and
cout << "You entered " << x << endl;
why do you use "std::" and what’s its purpose?
thanks.
std is the namespace that endl is defined inside of. I talk about this more in upcoming lessons.
oh thanks for the reply..
i think get it, you either use:
using namespace std;
or have to use std::cout ….std::endl
Yes. That said, it’s better to avoid using namespace std;
Hi Alex, Thank you for this tutorials
please can you use one cin statement to assign values to several variables of different data types. if yes please how. thank once again.
Enter 56a1.23 as input and you should get x=56, c=’a’, and d=1.23.
Alex, mate. You are an absolute legend! Love these tutorials and keep it up! PS: It’s awesome that you’re active in the comments section 🙂
I know this is very simple, but is this a good example of a clean, well formatted program?
I don’t fully understand floats yet, but I remember hearing somewhere that a float can hold a decimal value, so I tried replacing "int" with "float", & it worked.
I’m really liking these tutorials so far, and I’d like to give myself a little "recap" with this program here. Input would be much appreciated!
Yup, this is fine for where you are in the tutorials! We cover float in more detail in the next chapter.
Sweet, thanks! I’m reading up on return values now.
hullo alex!
thanks for these tutorials, they’re great.
i’m having a problem with the example code for std::cin - when i run it, all that appears in the console is this:
"5Press any key to continue…"
i press a key and the console closes.
i pasted your code directly into visual studio - is there something i’m missing here?
eamon
That’s what you should see after you’ve entered 5 and hit enter. It’s not waiting for you to enter a number?
Hi, Alex.
I tried something different. I just put pow(x,2) so I get the value I assign to x to the power of 2 and I tried what you said, to put a big number and see what happens, and everytime I try it my antivirus tells me that it has found an heuristic virus (I don’t know if these are the words in English but in Spanish it means that it doesn’t know what type of virus it is I think). For obvious reasons I guess it’s inoffensive, but I’d like to know why is it that my antivirus detects this piece of code as a potential menace.
Thanks for this site. 🙂
That seems really strange to me. I have no idea why this would be happening.
I forgot to say that it happened when I didn’t include <cmath>. Once I included that it didn’t gave any more trouble. Dunno if it helps… Anyway thanks for answering. 🙂
I get this error : /Error 1 error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup c:Userswindowsdocumentsvisual studio 2013ProjectsProject2Project2MSVCRTD.lib(crtexew.obj) Project2]
It sounds like maybe you created a Windows 32 project rather than a console project.
ok thanks!
Hi Alex, can you please tell me the difference between "endl" and "\n"? I also want to know which one is better among them. I have seen many answers on Stack Overflow but I am still confused with that.
I cover this in lesson 2.7 -- Chars.
Will do!
#include <iostream>
int cout() // declares our own "cout" function
{
return 5;
}
int main()
{
using namespace std; // makes std::cout accessible as "cout"
cout << "Hello, world!"; // uh oh! Which cout do we want here?
return 0;
What does it mean having 5 as a return value? My understanding so far, was that you placed a zero return value, to end a program, and something about a zero being shown if the program has no errors. What is the basics of these return values, what does it all mean?
I talk more about return values in the next lesson. Have a read and see if that answers your questions.
Thanks Alex for your prompt reply! Keep up the good work!
Hi Alex,
The std namespace
.
.
.
We’ll talk more about namespaces in a future lesson and also teach you how to create your own…..
.
.
.
Could you please tell me what the future lesson is?
The reason I am asking because I see a namespace(//define your own namespace to hold constants) in the last example of chapter 2.9. I go back to every previous section to see if I could find it somewhere for my review (how to define your own namespace), I don’t see anything related.
Thanks, Have a great day.
Lesson 4.3b. I’ll make a note on lesson 2.9 as well.
hi alex
1-you have said that cin and cout are functions live in std can we see what inside of them?
2-can we see what inside of the object file (.o)?
3-you are a very smart and Fabulous instructor do you have any other tutorial about Gui programming?
1) I’m not aware of an easy way to see what’s inside of the std namespace through your IDE, however there are plenty of good references on the internet (see)
2) Not really. There are tools that will let you view the symbols in an object file, but you probably won’t ever need to use it.
3) I don’t. I’d like to do some tutorials on GUI programming at some point, but there are so many other things I want to write about and so little time to write these days!
1)thank you very much.
2)can you tell me where can I Find these tools it is out of Curiosity I just want to see how the compiler turns my code and how it looks like.
3)can you give me the name of a good reference about GUI please.
1) You’re welcome.
2) It depends on your OS and compiler. If you’re using Windows/Visual Studio, check out
3) I don’t know of a good, general purpose reference for this.
What return 0; means ??
It means the function returns the value 0 back to the caller. The caller can then do whatever they want with this value (assign it, print it, ignore it, etc…)
Thanks admin , nice !
In VS2015, including <iostream> before "stdafx.h" dosen’t include the functions/stuff in <iostream>:
Why is this happening?
In Visual Studio, if you have precompiled headers turned on (and they are by default), #include “stdafx.h” _must_ be the first line.
I have a little confusion over here!
-----------------------------------
PROGRAM:
#include <iostream>
int main()
{
std::cout << "Enter a number: "; // ask user for a number
int x = 0;
std::cin >> x; // read number from console and store it in x
std::cout << "You entered " << x << std::endl;
return 0;
}
We already told computer that integer x is equal to 0 (int x = 0;)!??! Really confusing please help me!
For these two lines:
The first line tells the compiler, “hey, we’re declaring a new variable called x, and initializing it with the value 0”.
The second line tells the compiler, “hey, go ask the user for a new value for variable x”.
So, in essence, x gets the value 0, then we overwrite it with whatever the user inputs.
Thank you man, I got it!
Try this.The answer will always be 13. Remember to choose a number between 1 to 9.
____________________________________________________________________________________
#include <iostream>
int main()
{
cout << "Enter a number :";//ask use for a number
int x = 0;
cin >> x;//read number from console and store it in x
cout << "You entered :" << x << endl;
cout << "Please multiply the number by 9 and enter the answer :";
cin >> x;
cout << "You entered :" << x << endl;
cout << "Please add the first and second digit of the number and enter the answer :";
cin >> x;
cout << "You entered :" << x << endl;
cout << "Please add 4 to your new number :";
cin >> x;
cout << "You entered :" << x << endl;
return 0;
}
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
int main()
{
std::cout << "Enter a number:" std::endl;
int x = 0;
std::cin >> x;
std::cout << "You Entered" << x << std::endl;
return 0;
}
what is the problem,
why it shows this error
Severity Code Description Project File Line Suppression State
Error C2143 syntax error: missing ‘;’ before ‘std::endl’ ConsoleApplication1 d:\program practice\consoleapplication1\consoleapplication1\consoleapplication1.cpp 11
should be
Hi.
I just started using this website to learn how to code a couple days ago. I downloaded the Code Blocks IDE to my Mac. I have gone through all of the tutorials up until this point, and my first project was the HelloWorld program. Everything went fine with that. I wanted to create a new project so that I could enter this program that you recommended.
//#include "stdafx.h" // Uncomment this line if using Visual Studio
#include <iostream>
I encountered two problems:
1.) I went to New Projects and created a new console application that I titled Experiment. When I opened it in my Workspace and opened the sources under it, there was a file called main.cpp, which contained the HelloWorld program. I’m confused about how that got there, when my Experiment project is a completely separate project from the HelloWorld project.
2.) I deleted the HelloWorld program from the main.cpp file in my Experiment project. Then I pasted the above program from this tutorial. I built it and no problems popped up in my build log. I am in debug mode. When I clicked play, my terminal opened, but the program did not run as it should have. Nothing was printed to the console. The return value was 127. I clicked undo a bunch of times so the HelloWorld program was back in the main.cpp file under Experiments. Then I clicked run and build. The program ran and said Help World! Then I deleted the HelloWorld program and pasted the above program from this tutorial again and clicked build and run. Hello World! showed up on my console. What’s going on?
Thanks for your help and awesome tutorials. Sorry for the long message and perhaps dumb questions. I’m definitely a beginer.
I think Code::Blocks creates a simple “Hello world” program by default when you create a new project.
I’m not sure what’s going on with #2. I’d restart the app, create a new project, then try modifying the hello world program to make sure it’s running the program you think it is (e.g. make it write “Hello, moon!”). Once you’ve established that it is, then you can try pasting in the sample programs.
I’m having the same problem with HelloMoon!
There are some Program dependencies in Code::Blocks that I can’t seem to get around. Seems the program thinks I want the projects descending from one master project. It’s a bit frustrating…
For example I called the other project "EnterX" and it clearly is a new program, but in the Build Log of "EnterX" Code::Blocks stated:"Release in HelloMoon". I don’t get it.
Make sure you’re only creating each project individually (don’t try to put multiple projects in a master project). I’m not sure what else to suggest.
Hello, Alex. Thanks for the great tutorials.
After this tutorial, I’ve been reading Accelerated C++, by Andrew Koenig and Barbara E. Moo, and I came across this question in it.
Would this work as expected?
Why or why not?
I’ve been intrigued by this for a while. At first, I expected a few compiler errors, but the program compiled and ran perfectly.
C++ pretty much ignores the whitespace character (
is treated the same as
Does the compiler also ignore the newline character?
Is-
the same as
Yes, expressions and statements can be broken up across multiple lines. That’s why statements must end with a semicolon -- it tells C++ where the actual end of the statement is.
I am having a very tough time making any of these short programs to work. I copy and paste into my VS2010, and they will not build. Unsuccessful each time. Can’t run the program if you cannot build it. Example;
//#include "stdafx.h" // Uncomment this line if using Visual Studio
#include <iostream>
Error messages; 1>---- Build started: Project: std_cin, Configuration: Debug Win32 ----
1>Build started 3/21/2016 3:06:38 PM.
1>InitializeBuildStatus:
1> Touching "Debug\std_cin.unsuccessfulbuild".
1>ClCompile:
1> All outputs are up-to-date.
1> std_cin.cpp
1>c:\users\u081578\documents\visual studio 2010\projects\std_cin\std_cin\std_cin.cpp(2): warning C4627: ‘#include <iostream>’: skipped when looking for precompiled header use
1> Add directive to ‘StdAfx.h’ or rebuild precompiled header
1>c:\users\u081578\documents\visual studio 2010\projects\std_cin\std_cin\std_cin.cpp(15): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include "StdAfx.h"’ to your source?
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:04.48
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
You didn’t uncomment the first line. Remove the // before the #include so that “stdafx.h” gets included in your program.
I’m having a problem using Visual Studio 2015. For some reason when I press enter after inputting a number, ‘You have entered’ appears for a second and then the program is closed. I’ve looked at the common problems page and have tried, ‘return 0;’, std::cin.ignore(32767, ‘n’); and std::cin.get(); but it still does not work.
Here’s what it looks like:
#include "stdafx.h"
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int x = 0;
std::cin >> x;
std::cout << "You entered: " << x << std::endl;
std::cin.ignore(32767, ‘n’);
}
This site is really great by the way, thank you!
Try:
When I put in this code, I only get the first line printed. I don’t receive any errors or warnings.
Please let me know what I am doing wrong. Thanks
int main()
{
std::cout << "Enter a number: "; // ask user for a number
int x = 5;
std::cin >> x; // read number from console and store it in x
std::cout << "You entered " << x << std::endl;
return 0;
}
PS: Running Visual Studio 15
The “std::cin >> x” line is waiting for you to enter a value for x from your keyboard. Once you do that and hit enter, your program should continue.
Alex,
There is a minor error in this lesson. When you introduce std::cin above the output of the program will be printed on one line not two as shown.
<<std::endl can be mover up from line 9 to line 6 to fix this.
Incorrect. When we use std::cin to extract a value to variable x, the user will have to hit enter to end the extraction. That will cause a line break to occur, separating the output. Try it yourself.
Hi Alex. (Thank you for the toturial)
I have recent noticed that Compiler does’nt give error if you write either the one or the other one of the following:
# include "iostream"
OR
# include <iostream>
Which one is (more) Correct?
is correct. Use angle brackets for system header files, use double quotes for your own header files.
Hi brother, I need to know the way of reading the inputs at once and then doing the required operation and then displaying the output as in this case where a user receives the inputs-all at once and then prints them back(all at once) after the operation. Is there anyway without the arrays?
Sample Input:
2
10
20
Sample Output:
1
8
22
u can look at the problem here
I am not talking about the specific problem…but in general..
I know the logic of the above problem but I am stuck with the I/0..plz help.
Nope. Since the user is the one to enter how many inputs there are, you’ll need to use arrays (ideally dynamically allocated ones).
thank you brother alex
I’m kind of confused, what is the difference between the standard and iostream library or how are they linked?
The C++ standard library is a code library full of reusable functionality that you can use in your programs. Anything you see that uses prefix std:: is part of the standard library.
Iostream is a small part of the standard library that provides functionality to do console input and output.
Why do I have to say
when I can just say
and it will run just fine? Whats the point of assigning x to 0?
In this case, since the program asks the user for a value for x on the very next line, there’s no need to initialize x with a value.
However, I still often give my variables initial values anyway. That way, if I change the code (e.g. don’t ask the user any more) the variable will still have a known value.
In my opinion, it’s better to program defensively than optimize where it isn’t really needed.
Does anybody know why this code is wrong, code blocks says it was expecting a ; before the std but i tried putting a ; after int main() even thoug i know its wrong and it still doesnt work
Change
to
You’re missing the << operator for that line, and one other line further down.
// subtraction caculator
int main()
{
std::cout << "Enter the first number: " << std::endl;
int y = 0;
cin.get();
std::cout << "Enter the second number: " << std::endl;
int x = 0;
std::cin >> x;
std::cin >> y;
std::cout << "Your answer is: " << y - x << std::endl;
}
im trying to make a calculator for subtraction to start off and make something but after i get to the second number the program freezes any answers?
It’s not clear to me why you’re using cin.get(). Try this:
okay so, I tried to create a v small preset conversation, but after the first input, I got blasted with all the preset dialogue.
#include "stdafx.h"
#include "iostream"
int main()
{
using std::cout;
int x = 0;
cout << "Hello, my name is Alex… What is yours?" << std::endl;
std::cin >> x;
cout << "That’s a nice name.. can you help me…?" << std::endl;
std::cin >> x;
cout << "I’m trapped.." << std::endl;
std::cin >> x;
cout << "Inside your computer.. Just press the ‘x’ button in the top right to" << std::endl;
cout << "release me from this damned prison.. I will be most grateful…" << std::endl;
return 0;
}
Yes. Here’s what happening. You’ve defined x as a variable that holds an integer. Then you’re asking the user to enter text into that variable. std::cin >> x can’t figure out how to put text into an integer, so it fails (and that causes the rest of the std::cin statement to get skipped).
std::cin >> x
We’ll talk about how to deal with text in future chapters. It’s a little more complicated than dealing with integers.
turns out, the maximum value x can take is 2147483647, which when divided by 1024^3, gives a value pretty near to two. How that matters, i don’t know. 😛
learning c++ is so much fun…thank you so much for your effort Alex!!
playing around with example…:)
/ calcualtion test2 using namespace.cpp : Defines the entry point for the console application.
//
int main()
{
using namespace std;
cout << "Please use for addition of two or three integer variables" << endl;
cout << "Enter any first integer number " << endl;
int x = 9; // value 0 is given even its not necessary because initializing variables is a good habit
cin >> x;
cout << "Enter any second integer number " << endl;
int y = 0;
cin >> y;
cout << "Enter any third integer number (optional type 0 if not required)" << endl;
int z =0;
cin >> z;
cout << x << " + " << y << " + " << z << " = " << x + y + z << endl;
cout << "Have a nice day!! 🙂 " << endl;
Hi sir its SHUBH again with another query
instead i removed the int x = 0;
also when i dont put int x = 0 and instead type int x the program runs without any bugs
x is a variable, not a fixed value. You can assign different values to it.
In the first example, we assign the value of 0 to x, and then when the user enters a value, that overwrites the value currently in x with whatever the user entered. Giving x a value of 0 in this example is somewhat useless since it just gets overwritten anyway.
The second program shouldn’t compile since you’ve never declared x. You should at least need “int x” between lines 6 and 7.
The last std::endl is redundant in the example. It doesn’t matter whether you go to the next line or not if the program is going to end.
However, I personally put the std::endl there anyway, both for consistency, and because it helps avoid errors if new lines are added or reordered.
MR ALEX wonderful site absolutely loving it thanks for replying
Thanks for this awesome tutorial.
Thank you,Alex.Your tutorials are full of relevant informations and also well indexed.I’m writing this comment just to thank you.Love and grattitude from Bangladesh 🙂
Hi Alex,
with a premise that I am approaching C++ as a former (very former - something like 20 yrs ago) user of C, I’d like to ask you this:
is there a particular reason why you prefer going to the new line with the "<< endl" instead of adding the "\n" at the end of the string?
On my compiler (Code::Blocks with gcc 4.7.1 for Windows) they both give the same result, but "\n" is definitely faster to write than "<< endl".
Cheers
Mainly because at this point we haven’t talked about strings, chars, or special symbols. I cover both std::endl and ‘\n’ in future sections, and reasons to use one over the other.
But upon reflection, maybe it’s worth introducing earlier.
So far, this is perhaps one of the best tutorials I’ve ever used to learn something new. I would have never thought that programming is such an intuitive thing. 🙂
thanks
Great tutorials! Much better than the textbook I have to read!
This site is simply AWESOME!! But it will be better if you provide PDF format of the tutorial. So that we can refer the tutorial off-line too!!
Hi again Alex it's me again. So I've moved on to this lesson and now that it's happened again I'd like to see if we could get to the bottom of it.
My problem is that my console is auto closing as we discussed previously. This is great because I have questions now which will hopefully lead to me learning.
I'll break down the code and also what I'm doing to run it.
So this is the default code you asked me to use in the example on this lesson. When I put in this code (by the way I'm using VSPro2013) and then click the |> Local Windows Debugger, the program pops up, runs exactly how it should and then when I hit enter after typing a number it closes the cmd prompt window immediately after giving the output. This doesn't give me enough time to make sure it works right.
So I tried this
Which in turn gave me an error stating that cin was not identified so I had to do this:
That code fixed my problem but I'd like to get to the bottom of it if we could so I don't have that problem as I shouldn't by default. I'd like to know what your thoughts are.
Also why is cin unidentified in the first example? I'd really like to know.
Thanks Alex
Both cin and cout live inside the std namespace. If you use “cin” without any prefix, the C++ compiler won’t assume you mean std::cin. You either have to use std::cin, or use a “using” statement so the compiler knows that cin really means std::cin.
So I learned something new about Visual Studio today.
* If you run your program normally (“Start Without Debugging, keyboard shortcut ctrl-F5), Visual Studio will automatically pause at the end of your application.
* If you run your program with debugging (“Start Debugging”, keyboard shortcut F5), Visual Studio will not pause at the end of your application.
My suggestion is simply to run your programs without debugging, unless you need to debug. If you do need to debug, you can put a breakpoint on the closing brace of main() to ensure it stops.
(Note: I found a bug in the website that was causing your ‘\n’ to show up as '\n'. I fixed both the bug and your comment)
Great tutorial. Very well done. I have a question about expressions. Is the following considered an expression? It returns a value to the variable:
cin >> age;
I've been wondering about this and can't find an answer anywhere. Thanks!
I believe so. In this case, your operator is operator>>, and your operands are cin and the age variable.
Alex,
Does this cin create a variable. Wouldn’t you have to define the age variable first? This is how I have understood your tuts.
Thanks,
_aleph_
cin doesn’t create a variable, so yes, you’d have to define the age variable first, like this:
Hello Alex! This site is awesome!
Good job with the tutorials! I’m glad to see you keep active since some pages are from 2007.
I’m from Spain and it’s amazing to see I can understand the tutorials perfectly, I don’t need to read it twice to comprehend the content.
I only write to give thanks to you, you are helping me a lot. Keep this wonderful job!
I’m currently using Microsoft Visual Stuidos C++ 2010, but whenever I try to run the example scripts I get errors about the location of the file. Also, is there a different type of program I can download such as an interperator that compiles and runs the script automatically? I do not want to find the file and execute it every time I want to test something simple, such as defining different variables. Help would be appreciated.
Something is messed up with your installation. You shouldn’t have to locate the file and execute it every time.
I’d paste the error into Google and see if you get any hits on how to fix.
Sounds like when you initially installed the program you opted for another directory other than the default (usually used when a custom installation is selected).
I have seen with some programs this results in the type scenario you are describing.
You might check in your program options and then check the default directories to see where things are actually being saved and loaded from.
Name (required)
Website