Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ code wont run if a vector contains value

Tags:

c++

vector

I am using VS-Code and Vim, Windows OS, MSYS2 MingW GCC/G++ (V.11.2.0) compiler.

If my code contains a vector there is no output when I run the code. I get no error/warning when compiling or running the code.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main () {

vector<string> test = {"Why", "Wont", "This", "Run", "??\n"};
cout << test[0] << test[1]<< test[2] << test[3] << test[4];

cout <<"This is a test";
return 0;

}

If I comment out:

//vector<string> test = {"Why", "Wont", "This", "Run", "??\n"};
//cout << test[0] << test[1] << test[2] << test[3] << test[4];

I get the output: "This is a test"

I have tried reinstalling the compiler with no luck.

like image 551
Dsylexia Avatar asked Nov 02 '25 17:11

Dsylexia


1 Answers

I spent about 20 hours fighting this one and I lost -- at least on windows. My very smart friend said that there was "something wrong with my runtime" and recommended a fresh install of windows to try fixing it for that environment (I haven't tested that yet because I am lazy)

What did work was installing WSL (Windows Subsystem for Linux) and grabbing Ubuntu. C++ works as expected now, just launch VS Code through the bash terminal you'll get

Note: I had this same issue with a very similar setup. Laptop with VS Code, Windows 10, MSYS2 MingW GCC/G++ (V.11.2.0). If your error is very similar to mine, your code should run when the vector exists but does not have any contents. I could run C++ programs unrelated to vectors, or use vector's size() and empty() functions on empty vectors that were created. Allocating contents to a vector either on initialization or with push_back() was what prevented me from getting output. If you're able to compile other things and you have this issue without seeing extra info from -Wall, the compiler is probably fine but not the runtime. I feel that this is moreso correct because I made test programs, compiled the .exes, and they could be run by another computer, just not my own.

My other attempted fixes included uninstalling and reinstalling MSYS2 and its compilers, VS Code, Microsoft Visual C++ Redistributables, several restarts, and more. Windows itself is the last ditch effort, I'm just waiting on making a backup.

like image 130
Harris B Avatar answered Nov 04 '25 07:11

Harris B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!