std::ifstream::open inconsistent failure - c++

I was working on a project involving fstream when I ran into this inconsistency. My project is failing to open a .txt file and in attempting to debug it I created test.cpp which, as far as I can tell, is functionally identical to my main.cpp, however they output differently when compiled and run.
main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>
double get_pe(double price, double rent);
int main()
{
std::ifstream ifile;
std::string text;
std::vector<int> price;
std::vector<int> rent;
// ------------------------------ Problem 1 ------------------------------ \\
ifile.open("test.txt", std::ios::in);
if(ifile.is_open())
{
std::cout << "Works\n";
ifile.close();
}
else
{
std::cout << "Fails\n";
return 1;
}
return 0;
test.cpp
#include <iostream>
#include <fstream>
int main()
{
std::ifstream ifile;
ifile.open("test.txt", std::ios::in);
if(ifile.is_open())
{
std::cout << "Works\n";
ifile.close();
}
else
{
std::cout << "Fails\n";
return 1;
}
return 0;
}
Console Output
$ g++ main.cpp | g++ test.cpp -o t.out
$ ./a.out
Fails
$ ./t.out
Works
$ ls
a.out housingPriceAndRent.txt main.cpp streetAdresses.txt test.cpp test.txt t.out
$ g++ --version
g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
I'm really interested in what's causing this, but I haven't the slightest clue.

Your issue is here:
// ------------------------------ Problem 1 ------------------------------ \\
Looks pretty benign right? Just a comment? But the problem is that escape character at the end. That's your way of saying "ignore this linebreak and treat the next line as if it was on this one."
So the next line:
ifile.open("test.txt", std::ios::in);
is actually part of that comment!! You never run that ifile.open()--so of course ifile.is_open() will be false!
I would expect any IDE worth its salt to have colored this this properly so you could quickly see that that line was a comment (that's how I caught it). Notice how for me, line 18 looks green like a comment:

Related

mingw compiled executable does not output characters in powershell/cmd

I tried to use the following code to output files in current directory
#include <filesystem>
#include <iostream>
using namespace std::filesystem;
int main() {
for (directory_iterator next("."), end; next != end; ++next) {
std::cout << next->path() << std::endl;
}
return 0;
}
the compile command is a simple g++ demo.cpp -o demo.exe, the path to g++ is C:\msys64\ucrt64\bin\g++.exe.
It worked properly when i ran it in bash (msys2),
$ ./demo.exe
".\\.clangd"
".\\.vscode"
".\\demo.cpp"
".\\demo.exe"
but when i did the same thing in powershell or cmd, it output nothing.
PS C:\Users\cnjawi> .\demo.exe
PS C:\Users\cnjawi>
The following code could run just fine in powershell and cmd.
#include <filesystem>
#include <iostream>
using namespace std::filesystem;
int main() {
std::cout << "test\n";
return 0;
}
However, if i add the original code, the issue occurs, even the "test" couldn't be output.
#include <filesystem>
#include <iostream>
using namespace std::filesystem;
int main() {
std::cout << "test\n";
for (directory_iterator next("."), end; next != end; ++next) {
std::cout << next->path() << std::endl;
}
return 0;
}
Thanks to HolyBlackCat's comment. When i double-clicked this program, Windows prompted The procedure entry point ~ could not be located, which gave the key info -- the program doesn't actually work in powershell due to some missing DLLs, rather than working but not outputting.
However, a collapsed program does not issue warnings in powershell, which made it appear to have worked "normally".
The simplest way to solve it is using the static library. For this instance, use g++ -c demo.cpp to generate demo.o and then g++ -static demo.o /ucrt64/lib/libstdc++fs.a -o demo.exe(in bash).

VSCode creating string in c++ doesn't work

Trying to figure out why creating an instance of a string results in my program being shut down...
My simple program is:
#include <iostream>
#include <string>
int main(){
std::cout << "HELLO" << std::endl;
std::string str("str");
return 0;
}
My problem is that this program prints nothing. However:
#include <iostream>
#include <string>
int main(){
std::cout << "HELLO" << std::endl;
// std::string str("str");
return 0;
}
works perfectly fine and prints "HELLO".
I'm compiling with mingw this way: g++ main.cpp -o main.exe (doesn't show any errors)
I've tried using the string in any way (like printing it). In general I'm trying to create a string instance to do std::cin>> into it.
Help will be much appreciated! Thank you
Works for me:
$ cat test.cpp
#include <iostream>
#include <string>
int main(){
std::cout << "HELLO" << std::endl;
std::string str("str");
return 0;
}
$ g++ test.cpp
$ ./a.out
HELLO
$
The problem is elsewhere in your system, the code is OK.

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

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).

File fails to open with fstream C++ on Mac OSX

Alright, so I could have sworn this worked in my program earlier, but now I'm being driven mad by std::fstream. I just want to open a file from command line arguments, ie.
./main Program1.S
should open the file Program1.S and scan it.
Here is how I set up a open_file() function in my code:
#include <string>
#include <iostream>
#include <fstream>
void open_file(std::fstream &ifp, std::string file_name) {
ifp.open(file_name, std::ios::in | std::ios::out);
if(ifp.fail()) {
std::cout << "File not found." << std::endl;
exit(1);
}
}
void close_file(std::fstream &ofp) {
if(ofp.is_open()) {
ofp.close();
return;
}
std::cout << "This file is not currently open" << std::endl;
}
int main(int argc, char * argv[]) {
std::string in_name;
in_name = argv[1];
std::fstream ifp;
open_file(ifp, in_name);
// do some processing
close_file(ifp);
return 0;
}
Now, I compile my program using (unfortunately I am required to use c++03): g++ -g -std=c++03 -Wall -pedantic main.cpp -o main
Compilation works and provides no errors, but when running the program using: ./main Program1.S, it goes to File not found in open_file(). I even checked what was in argv[1] and it is definitely a file that is in the current working directory. Is there something wrong with the way I am doing this?
Check to make sure your file has been added to your project folder. Otherwise, you need to specify a file path within your computer ex. "/Mac HD/Documents/myfile". The program has no idea what to do with a external file name without its file path. Hope this helps.

C++ std::cout and string printing in wrong order

I have a simple program running on Linux using g++ compiler:
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv){
fstream file;
string s;
file.open("sample/dates.dat", fstream::in);
if(!file.good())
return 0;
getline(file, s);
cout << s << "." << endl;
return 0;
}
Compiled with: g++ -o test test.cpp. When I run this, the fullstop is printed BEFORE the string s, not after. Does anybody know why this is happening? And is it easy to fix?
Thanks.
If there is a carriage return at the end of the string it will move the position of output to the beginning of the console line when printed.
#include <iostream>
int main()
{
std::cout << "some line\r" << "." << std::endl;
// ^^ carriage return
}