C++ using g++, no result, no print - c++

I'm slowly moving from using Python to using C++ and I don't understand how to run any code. I'm using the g++ compiler, but I get no results from my functions.
// arrays example
#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; ++n )
{
result += foo[n];
}
cout << result;
return 0;
}
If I run this example inside VSCode and specify that I want to use g++ compiler it comes back with: Terminal will be reused by tasks, press any key to close it.. If I compile it through cmd and run the task, a new cmd window flashes and nothing is happening.
I found the g++ doc which says how to compile with g++ and it shows the following example:
#include <stdio.h>
void main (){
printf("Hello World\n");
}
But I can't even run the compiler because it says
error: '::main' must return 'int'
void main(){
^
How can I print something in cmd or the ide terminal? I don't understand.

I believe you are using VSCode in a wrong way. You must know that it does not have integrated compiler by default but you need to compile source file in command line and run the executable:
$ g++ hello.cpp
$ ./a.out
Your first example runs with no problem. Check here
Your second example has an error because there is no void main() in C++. Instead, you need to have
int main() {
return 0;
}
UPDATE
If running the executable results in opening and closing the window you can fix that by using one of the following:
shortcut
#include <iostream>
using namespace std;
int main() {
system("pause");
return 0;
}
preferred
#include <iostream>
using namespace std;
int main() {
do {
cout << '\n' << "Press the Enter key to continue.";
} while (cin.get() != '\n');
return 0;
}
Why std::endl is not needed?
Some of the comments are suggesting that changing
cout << result;
to
cout << result << endl;
will fix the issue but, in this case, when the above line is the last line in the main function it really does not matter since program's exit flushes all the buffers currently in use (in this case std::cout).

Related

Arguments passed to the command line not printed and the program loops indefinitely

I'm trying to implement a simple command line program that takes three arguments and prints them on the linux terminal
For example:
>c++ exec.cpp
>./a 32 + 32
Should print out contents like this
32
+
32
But the program is looping indefinitely
I've implemented a check for argc
Like this
if(argc!=3) {
cout << "Exit" << endl;
return -9999;
}
In case the argument count is 3
These lines of code should be executed
else {
for(int i=0;i<argc;i++){
cout << argv[i] << endl;
}
}
But as I explained before the program loops indefinitely
EDIT:
Since I was asked to post the entire code here it is
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc,char* argv[]) {
if(argc!=3) {
cout << "Exit" << endl;
return -9999;
}
else {
for(int i=0;i<argc;i++){
cout << argv[i] << endl;
}
}
}
Your code is working...
I made slight modifications (eg. argc !=4 , i <= argc , etc. )
I compiled it using gcc (g++) on my linux system using:
g++ exec.cpp -o a.out
./a.out
Output:
Exit
When I run:
./a.out 4 + 3
Output:
4
+
3
Now with code, that does look okey to me in fact.
There doesn't seem to be a way to have an endless loop in every case.
What happens if you add return(0); to the very end of the main function?
Main always has to return something and compilers normally either complain or do that on their own hwoever if the propgrammer didn't add it.
Oh, have you tried the cerr variant instead of cout for your error message? Because returning from the main right after, is quite the same as the crash I mentioned.

g++ compiles c++ script with #include-statements to .exe-file which fails to run

I have the following script in C++:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector <string> markus = { "M", "A", "R", "K", "U", "S" };
for (int i = 0; i < markus.size();i++) {
cout << markus[i];
}
return 0;
}
I have successfully installed g++. When I try compiling this code with the command g++ -o test test.cpp, I get no errors. However, when I try running the created test.exe-file, with the command test, I get an error saying "could not find starting point". First, there is a long sequence, then the following message; "The starting point for the procedure could not be found in the library for dynamical links", and the the absolute path for test.exe.
If I remove #include <vector>, and try the following code;
#include <iostream>
using namespace std;
int main() {
cout << "Hello world";
return 0;
}
, it works perfect.
I would be glad for the help.

Code blocks runing error: Build failed

I am new to C++, and now learning it using code blocks (version: codeblocks-16.01mingw-setup.exe). My test codes are as follows:
#include<iostream>
#include<stdlib.h>
int main()
{
int sum = 0, val = 1;
// keep executing the until val is greater than 10
while (val <=10 ) {
sum += val; // short-cut assignment
++val; // add 1 to val
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
system("pause");
return 0;
}
These codes are written in an empty file named ex1.cpp. Then I tested by click "Build and run". As a result, another file main.cpp (I did not write this) pops up:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
return 0;
}
Screenshot attached for your better checking:
The reason why you are getting this error is because your compiler settings is not correct.You need to make sure that you use GNU GCC MinGW Compailer.Go To Settings-->Compiler and make sure every thing is same as on the screen shot.
Solving common codeblocks problems :Link
I really did something wrong about coding:
when I create an empty file in the project, it will result in two main functions in the that project one of which is that "hello world" file automatically generated, which is not allowed by C++.
To build it successfully, what I did is to overwrite the codes in the main.cpp.

What to do to see the output of "cout" command?

I am starting with C++ (Visual Studio 2015 and Windows 8.1), with this simple code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
return 0;
}
But, the output screen shows nothing!, what shall I do?
Thanks in advance.
In Visual Studio, start the program with Ctrl-F5 and it will run and pause automagically for you. No additional code needed.
Your code is perfectly fine but the program currently only prints and exits right after, because this can happen very fast you might not be able to even see it,try pausing it :
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
cin.get();
return 0;
}
Also, make sure your Anti Virus isn't blocking Visual Studio.
Your code is just fine, however, if you execute it as a cmd program, the program window will close immediately, you might not be able to even see the output. You can write extra code to solve this problem by "pausing" the program:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
cout << "Hello world" << endl;
system("PAUSE");
return 0;
}
if you don't like include a windows.h file every time you type, you can add a "cin.get();" in the end of the code. But to be honest, since you are just a beginner, the coolest way I think you should try, is not to use Visual Studio to learn C/C++ but to install CodeBlocks(a simple but effective IDE) to write some codes that are not so long. You know, VS is for huge and complex projects and some practical program developing.
Another solution, platform dependent. My answer is for those of you who just need test pause for debugging purposes. It's not recommended release solution!
windows
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
system("pause");
return 0;
}
linux (and many alternatives)
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
system("read -rsp $'Press enter to continue...\n'");
return 0;
}
Detecting paltform
I used to do this on programming homework assignments, ensuring this only happens on windows:
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
#ifdef _WIN32
system("pause");
return 0;
}
Here's a good cheatsheet for ifdef macros and operating systems: http://sourceforge.net/p/predef/wiki/OperatingSystems/
The program exits on return 0; and window closes. Before this, you must pause the program. E.g you can wait for an input.
Here is a snippet from my code to do this. It works in both windows and linux.
#include <iostream>
using std::cout;
using std::cin;
// Clear and pause methods
#ifdef _WIN32
// For windows
void waitForAnyKey() {
system("pause");
}
#elif __linux__
// For linux
void waitForAnyKey() {
cout << "Press any key to continue...";
system("read -s -N 1"); // Continues when pressed a key like windows
}
#endif
int main() {
cout << "Hello World!\n";
waitForAnyKey();
return 0;
}

Dev-C++ Hello world doesn't show

I am new to C++. I downloaded and run Dev-C++ and I write and run F9 this:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!";
return 0;
}
But no "Hello, world!" is printed, why?
Many IDE users have this problem. The program runs but it closes before you can see its results on the screen. One portable fix is to add this at the bottom of main before you return:
std::cin.get();
That way it will wait for you to enter some text before it exits.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!";
getchar();
return 0;
}
Add getchar() at the end of your program as a simple "pause-method" as consoles seems to close so fast, so you need to "delay" to see your console.
The output is printed to a terminal, and you don't have a newline etc.... very unlikely that you will see it, so
Add a newline to the output
make sure you have time to read the output before the terminal window closes (add a sleep or something)
Don't use using namespace as that is a bad practice and will lead to trouble in your programming.
So like;
#include <iostream>
#include <unistd.h>
int main()
{
std::cout << "Hello, world!" << std::endl;
sleep(2);
return 0;
}