G++ Compiles, Executable Won't Run - c++

I've been using a text editor and g++ to compile and run programs for a while, but for some reason, it stopped working today.
It will compile without errors but when I try to run the executable, it doesn't do anything. No errors, no output. Nothing. This is the code I'm trying to run.
#include <iostream>
#include <fstream>
int main(){
// Initializes variable.
int coordinatePair;
// Creates an object to use for the file.
std::ofstream fileReader;
// Initiates a for-loop to get the value of each variable.
for(int i = 0; i == 5; i++){
std::cout << "Please enter the x-coordinate of your coordinate pair. " << std::endl << "You have " << 5 - i << " pairs left to enter." << std::endl;
std::cin >> coordinatePair;
// Opens the file.
fileReader.open("points.txt");
// Writes the user's values to the file.
fileReader << coordinatePair << std::endl;
// Closes the file.
fileReader.close();
}
}
In the terminal, I created a directory to the file location...
cd ~/file location
And then I compiled it.
g++ points_out.cpp -o points_out
And I tried to run it.
./points_out
And nothing happens. No error messages, no output, no nothing. While the code isn't exactly efficient (I'm probably better off opening and closing the file outside of the for-loop.) it should still run. I tried putting in incorrect code to see what would happen, and it gave me the proper error codes. I also tried
g++ -W -Werror points_out.cpp
...and that didn't give me any error codes either. I tried making a new directory to a different .cpp file I had compiled and ran earlier this week and it worked just fine. For some reason, this one just will not run. And I'm confident that it is compiling because the executable is being created. I'm also confident that it is not running, because the text file is not being created.
I got this thing to compile successfully and run once and it created the text file when it did. This is the first time I've run into issues with g++. I've looked everywhere for a solution but most of the people who had this problem just weren't doing the
./points_out
part or had issues with MingW or needed to uninstall Avast. None of these are the issue I have so I'm at a loss.
Also, not sure if this will help, but running
g++ --version
gets me the following output:
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The behavior is normal for a program doing nothing and completing successfully.
The C++ for-loop evaluates the loop condition before entering the loop body. When the loop body is completed, the optional post-loop expression is evaluated and the program returns to the conditional check.
So your code assigns the value 0 to i and then tests to see if i == 5 before allowing entry into the loop.
It's not entirely clear what you were intending, but you probably mean't
for (int i = 0; i < 5; i++)
We can demonstrate that quickly with this piece of code:
#include <iostream>
int main() {
std::cout << "original loop:\n";
for (int i = 0; i == 5; i++)
std::cout << i << '\n';
std::cout << "corrected loop:\n";
for (int i = 0; i < 5; i++)
std::cout << i << '\n';
}
Live demo: http://ideone.com/O0Ul2z
-- Addendum --
Most programmers would have thought to add something like a no-frills, no-conditions
std::cout << "hello world\n";
at the top of their program to verify that it wasn't running vs not working.

Related

C++ not printing emojis as expected

I have the following extract of a program
int main(){
cout << "1) ✊\n";
cout << "2) ✋\n";
cout << "3) ✌️\n";
}
But at the time I run it I get strange texts like the following
====================
rock paper scissors!
====================
1) 
2) 
3) ԣÅ
This seems not to be related to my terminal but instead to a compilation result because if I run echo ✊ it shows as expected.
See example below
I'm currently using the following compilation commands and compiler version
g++ *.cpp -o rock_paper_scissors.exe
g++.exe (Rev9, Built by MSYS2 project) 11.2.0
Copyright (C) 2021 Free Software Foundation, Inc.
Finally, note that it was working before as expected, but at some point, it stopped working, I noticed after I used system("pause") which I'm guessing may have changed something on the compilation configurations as this is a Windows-only command, I delete such piece of code and still having the issue.
You can see the rest of the code here: https://github.com/guillene/RockPaperScissors
If your terminal font supports emojis and you don't want to write much code (like switching from cout to wcout), you can use the windows api function below.
#include <windows.h>
#include <iostream>
int main(){
SetConsoleOutputCP(CP_UTF8);
std::cout << "1) ✊\n";
std::cout << "2) ✋\n";
std::cout << "3) ✌️\n";
return 0;
}
see: https://learn.microsoft.com/en-us/windows/console/setconsoleoutputcp

Error When Trying to Compile in Eclipse (MacOSX)

I am learning Eclipse and C++ and am working on an extremely simple program. I can't build the program now. I just recently installed HomeBrew so I don't know if that has something to do with it. Here is my code (it's from a simple tutorial I'm working off of so I know the code works because I've seen it work on the tutorial):
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Ask the user to input a word while the word length < 5
string word = "";
do
{
cout << "Enter a word that has at least 5 characters: " << endl;
cin >> word;
}while(word.size() < 5);
// Ask the user to input a character
char searchCh = '0';
cout << "Enter a character and the program will tell" <<
" you how many times it appears in the word " << word << "." << endl;
cin >> searchCh;
int counter = 0;
// Iterate over the word
for(int i = 0; i < word.size(); i++)
{
// Get a character
char ch = word.at(i);
// If the character matches the character we're looking for
if(searchCh == ch)
{
// Increment a counter
counter++;
}
}
// Output the number of times the character was found in the word.
cout << "The number of " << searchCh << "'s in the word " << word << " is " << counter << "\n";
return 0;
}
The error I get when build is this:
g++ -o "Program 5" ./Program5.o
Undefined symbols for architecture x86_64:
"_main", referenced from:
implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Program 5] Error 1
I've seen several other similar question on here about going to 'Project' and 'Properties' but I don't know what settings exactly are supposed to be updated to get this working. Also, some of the other answers mentioned that a main() function is needed to fix this issue, but I obviously have one in this code. It was working fine last week when I was using Eclipse on other small projects so I'm not sure what changed.
For further information:
When I first the set the project up, it is set as an 'Empty Project' project type with 'MacOSX GCC' as the toolchain. I then created a source file (with the .cpp extension) within the project, wrote the code, and then that's where I'm at.
Any help would be greatly appreciated. Thanks!
Try resetting up your project. Sometimes installing buildchains can confuse eclipse and make it use the wrong libraries - especially if it is expecting another version.
What I think happened here is that eclipse confused was using a buildpath that did not contain C++ files (due to an upgrade moving them?) but instead contained C files, which don't link with C++ under normal circumstances.
As also mentioned by another commenter, this could also be the result of an initial failed build not being cleaned up for some reason.
Sometimes with eclipse, the solution is the same as with Windows: Restart it, redo whatever went wrong again.

In Embedded Octave C++ how do I execute a script file? ("error: invalid call to script")

I am writing a c++ oct-file that I would like to use as a link between my c++ code and scripts that were written in Octave. I can build and execute with no problems, and as long as I am doing simple things, it seems to work. I can even call functions in a script file with feval()! I just can't seem to figure out how to execute an entire script file..
If I try this simple program, I get an error, but I'm not sure why
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/toplev.h> // for do_octave_atexit
#include <iostream>
#include <string>
using namespace std;
void runscript(const string &file) {
cout << "attempting to run: " << file << endl;
int parse_status = 0;
eval_string(file, false, parse_status);
cout << "parse_status: " << parse_status << endl;
eval_string(file, false, parse_status, 0); // I'm not sure what the difference here is or
// what the value 0 means, I can't find any documentation on
// what `hargout` is.. See Note {1} below
cout << "parse_status: " << parse_status << endl;
}
int main(int argc, char **argv) {
// Set-up
char *oct_argv[3] = {(char*)"embedded", (char*)"-q", (char*)"--interactive"};
octave_main(3, oct_argv, true);
// Attempt to run script
runscript("Script1");
runscript("Script1.m");
// `a` should be defined after running Script1.m..
octave_value_list a = get_top_level_value("a", false);
do_octave_atexit ();
return 0;
}
Script1.m is very simple and looks like this:
a = 1000;
a
When I run, I always get this output:
attempting to run: Script1
error: invalid call to script /Users/Daly/Documents/School/EECS/Labs/GitHub/deep/Octave/ Script1.m
parse_status: 0
parse_status: 0
attempting to run: Script1.m
parse_status: 0
parse_status: 0
error: get_top_level_value: undefined symbol 'a'
It only ever complains about the invalid call the first time, no matter how many times I try to eval_string or in what order.
Notes: {1} After searching for error: invalid call to script, I found this source code which at line 00155 raises this exact error if nargout isn't 0, so I thought they might be related?
But anyway, maybe this isn't the right way to be going about it. What is the correct way to execute an entire octave script from an octave-embedded c++ program? Thanks!
You should be using the function source_file() rather than eval_string(). Take a look into the parser.h file which unfortunately doesn't have a lot of comments. The names are quite self-explanatory so you shouldn't have a lot of problems.
Also, you're pretty much trying to reimplement Octave's source function. If you really want to implement it again, look into the oct-parse.cc file (generated during the build process with flex and bison).

gnu slist execute error: lost of file .../bits/allocator.h: No such file

I'm using Ubuntu. g++ version 4.7.2.
Can anyone help me with the gnu-extension single list? I compiled the stuff here and got a core dump when executed.
I debuged it and saw the core dump happend in the first line, where it throwed an error that I cannot solve. May anyone please help me with that??
the error code:
std::allocator<char>::allocator (this=0x7fffffffe4d0)
at /build/buildd/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/bits/allocator.h:104
104 /build/buildd/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/bits/allocator.h: No such file or directory.
This is my test code:
#include <ext/slist>
#include <cstring>
#include <iostream>
int main(int argc, char * argv[])
{
__gnu_cxx::slist<char> li(&argv[1][0], &(argv[1][strlen(argv[1])]));
if(argc != 3)
return 1;
std::cout << "SList: ";
for(__gnu_cxx::slist<char>::iterator i = li.begin();
i != li.end();
++i)
std::cout << *i;
std::cout << std::endl;
li.remove(argv[2][0]);
for(__gnu_cxx::slist<char>::iterator i = li.begin();
i != li.end();
++i)
std::cout << *i;
std::cout << std::endl;
return 0;
}//main
My guess is that you're not giving any command-line arguments when you run it. It expects two: the character sequence to put in the list, and the character sequence to remove.
UPDATE: as mentioned in the comments, to pass the arguments to your program when using gdb, you need to use the --args option to indicate that arguments following the program name should be passed to the program, not to gdb itself:
gdb --args a.out xxyyxx x
^^^^^^
It initialises the list from the first argument argv[1] before checking that that argument exists; if it doesn't, then you'll get undefined behaviour. If you move the check above the declaration of li, then the program should exit with return code 1 instead in that case.
Then the debugger complains that it can't find the source file, and so can't show you on which source line it went wrong.
By the way, the C++ standard library now includes a singly-linked list, std::forward_list, defined in <forward_list>, which you could use instead of GNU's extension.

Compiler throws cout'ing out of loop

I wrote a numerical simulation and, as a tweak, I wanted to add some basic progress bar.
In the main loop I wrote:
if(particles.t>=pr*maxtime){
cout << "|";
pr+=0.01;
}
Where pr starts at 0.01. So, basically it was supposed to cout one hundred "|" during the computation. Instead of that it couts these "|" at the end of the simulation, all at once.
And when I modify this code to:
if(particles.t>=pr*maxtime){
cout << pr << "\n";
pr+=0.01;
}
it works as it should.
I guess it have something to do with optimization, I am compiling my code using g++, with options -Wall and -lm. Code like this worked when I wrote it in C#, a while ago.
The problem is with the buffering of the output. Place cout.flush(); after each printing and the issue should be solved.
The writes to cout (and many other streams) are buffered. If you want to make them immediately visible, you need to flush the stream:
if(particles.t>=pr*maxtime){
cout << "|";
cout.flush();
pr+=0.01;
}