So, I'm new to C++. I need to learn this language quick for school. But I'm walking against some issues that make it difficult to work with this language. I downloaded visual studio code and followed the steps given by my school. But now I have the problem that sometimes my code just won't print.
Here is an example of a piece of code that does print (btw, I use a "makefile" to run all of this):
#include <iostream>
int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}
Ofcourse, just a simple "hello world" but still, it does print. Now I'll give an example of a piece of code that won't print:
// C++ program to sort an
// array using bucket sort
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Function to sort arr[] of
// size n using bucket sort
void bucketSort(float arr[], int n)
{
cout << "hello" << endl;
// 1) Create n empty buckets
vector<float> b[n];
// 2) Put array elements
// in different buckets
for (int i = 0; i < n; i++) {
int bi = n * arr[i]; // Index in bucket
b[bi].push_back(arr[i]);
}
// 3) Sort individual buckets
for (int i = 0; i < n; i++)
sort(b[i].begin(), b[i].end());
// 4) Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < b[i].size(); j++)
arr[index++] = b[i][j];
}
/* Driver program to test above function */
int main()
{
cout << "hello" << endl;
float arr[]
= { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 };
int n = sizeof(arr) / sizeof(arr[0]);
bucketSort(arr, n);
cout << "Sorted array is \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
This is an example of a bucket sort I found online. First, the "n" on the vector<float> b[n] line, gave a red line, I chose the "ignore this error" option. Second, this code won't output anything. If I look into the "debug console" I find this error: ERROR: Unable to start debugging. Unexpected GDB output from command "-exec-run". During startup program exited with code 0xc0000139.
When I looked online I saw some people give the advice to downgrade my gdb version. I want to try that, but I can't find out how to do that haha. Can someone help me get my visual studio code working? This is the most irritating part of programming to me.
ERROR: Unable to start debugging. Unexpected GDB output from command "-exec-run". During startup program exited with code 0xc0000139.
This error means that the program didn't start at all, i.e. died during process setup.
On UNIX this usually happens when the GDB exec-wrapper dies. But I have no idea how VSCode sets up GDB and under what conditions it would die like this.
General advice:
if you want to learn GDB, and you insist on using Windows, then learn GDB in a WSL2 environment.
if you don't want to learn GDB, learn debugging using Visual Studio
you should always learn "native" debugger for the OS you are using -- that way you avoid having to debug various "shims" which (imperfectly) emulate one environment inside another (as appears to be the case here).
Related
#include <iostream>
#include <vector>
using namespace std;
typedef vector<string> VS;
void back(VS ¶ules, VS &sol, int n, int i) {
if(i == n) {
cout << "{" << sol[0];
for(int j = 1; j < n; j++) {
cout << "," << sol[i];
}
cout << "}" << endl;
}
else {
for(int j = 0; j < n; j++) {
sol[i] = paraules[j];
back(paraules, sol, n, i+1);
}
}
}
int main() {
int n;
cin >> n;
VS sol(n);
VS paraules(n);
for(int i = 0; i < n; i++) {
cin >> paraules[i];
}
cout << "This won t print";
back(paraules, sol, n, 0);
}
Pasted the whole code now. A backtracking that takes n words, and just prints all the permutations of the words.
I initially thought it was a problem with the reading since the this wont print wasn't printing. After some testing, I've discovered that commenting the function call on the last line makes the error disappear, and the code doesn't crash anymore.
So it's maybe the function? This still doesn't explain why it's not printing, since the call happens after the cout.
As an example input might be:
2 hi bye
It appears that you are going out of bounds in your back function for loop due to the if statement, try using n-1 instead
if(i == n-1)
The problem is that for the case when i == n is true, you've the statement:
cout << "," << sol[i]; //this leads to undefined behavior
In the above shown statement, the size of the vector sol is n. But note since i is equal to n in this case, you are going out of bounds by writing sol[i] and this will result in undefined behavior.
This is because, the indexing starts from 0 and not 1.
For example, say the vector sol size is 4. That is n = 4.
Now what you're essentially doing is :
cout << "," << sol[4];
But you can only safely use elements upto index 3, i.e., using sol[0], sol[1], sol[2], sol[3] is safe. On the other hand, using sol[4] leads to undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
For example here the program doesn't seem to crash but here it does crashes.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
I don't believe there is an issue with the code itself. You are getting segment faults, but it would be from something else.
However, I am assuming your code looks like this:
#include <vector>
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
vector<string> v(n);
for(int i = 0; i < n; i++) {
cin >> v[i];
}
}
Because your code is missing a ending parenthesis, and a #include <iostream>. Would you mind copy and pasting your entire code, or linking a repository?
I am currently trying to make the Conway's game of life in c++ for a school project. The problem is I don't know how to make the board more "dynamic". How can I return several lines to change the output I made before? Right now I have to print various boards which isn't exactly aesthetic.
Looking this up on previous questions I could only find "/r" which helps if the board is only one line, but in my case it isn't.
Edit: Added code sample (if it helps).
for (int temp = 0; temp < iterations; temp++){
for(long long i = 0; i < height; ++i){
for(long long j = 0; j < width; ++j){
if (CurrentGen[i][j]){
cout << "■" << " ";
}
else{
cout << "." << " ";
}
}
cout << "\n";
}
cout << "---------------------------------------" << endl;
CurrentGen = NextGen(CurrentGen, height, width);
sleep(1);
}
This will end up being more than complicated solution for the system dependent code.
However the easy and quick solution is for visually having the same line being updated is to create many empty lines for every loop iteration.
for (int n = 0; n < 50; n++)
{
std::cout << "\n";
}
As I said earlier this is the best C++ could do when there is no system information available, using only the standard commands.
There are other ways to do it such as:
system call to clear the terminal
but this method not safe
The standard way to print end lines
Using the ncurses library #include <curses.h>
Advantage: it is a cross-platform
Disadvantage: cannot be mixed with standard I/O
i was generating output from txt, and the input from txt too, but, the the txt file is 79MB. I don't know why it's stopped working, and also, i use loop for the input, the line in the input text is 9.000.000 lines, so i need to loop 3000^2 , but i don't know what's wrong, it's just crashing after i compile it.
Here's the code
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
freopen("hex.txt","r",stdin);
freopen("css.txt","w",stdout);
cout << ".container{\nwidth: 3000px;\nheight: 3000px;\n}\n";
cout << ".px{\nfloat: left;\nwidth: 1px;\nheight: 1px;\n}\n";
string hex[3000][3000];
for (int i=0; i<3000; i++)
{
for (int j=0; j<3000; j++)
{
cin >> hex[i][j];
}
}
for (int i=0; i<3000; i++)
{
for (int j=0; j<3000; j++)
{
cout << ".b" << i+1 << "k" << j+1 << "{\nbackground: "<< hex[i][j] << ";\n}" << endl << endl;
}
Note: hex.txt size is 79MB, and when it stopped working, the "css.txt" (output file) is not exist, i'm sure it's crash when the program trying to reading freopen("hex.txt","r",stdin);
i use Codeblocks 16.01 also if i remove the line 5 in the code, it's still crash, and i just debug it in my codeblocks it said segmentation fault, how do i fix this? thanks!
EDIT: Problem solved by cout immediately after cin, and that's work! i didn't try using vector yet, but now i know that using string hex[3000][3000] didn't work because the space is too small.
Sorry my bad english.
string hex[3000][3000];
Stack space is too small to allocate large arrays, you can use vector<vector<string>> to avoid this situation.
Such as
vector<vector<string> > hex(3000, vector<string>(3000));
I am taking a course on visual C++ and according to the text, the following code should work (exact copy and paste of the text). Intellisense is saying otherwise, claiming there are 5 errors (informing me that cnt2: undeclared identifier, missing ";" before "{" and missing ";" before "}"). I have never attempted this before with any language (quite honestly didn't know it was a possibility), so any enlightening would be appreciated!
#include <iostream>
// Program 2.: Program demonstrates the for-loop.
int main()
{
using namespace std;
for (int cnt1 = 0, int cnt2 = 9; cnt1 < 10; ++cnt1, --cnt2)
{
cout << cnt1 << "---Hello, World!---" << cnt2 << endl;
}
}
Exact text from my book:
This time there are two counter variables (separated by commas), which are initialized to 0 and 9. Moreover, one is incremented and the other is decremented. Consequently, as shown from the output, one counts forward and one counts backwards. Part 2-the condition-remains the same; that is, it still specifies that we loop ten times.
What am I doing wrong here? Does visual studio 2013 professional not allow this operation? The text said to use Visual C++ to program, I am just more comfortable with VS.
Your code should be like this
// Program 2.: Program demonstrates the for-loop.
#include <iostream>
int main()
{
using namespace std;
for (int cnt1 = 0, cnt2 = 9; cnt1 < 10; ++cnt1, --cnt2)
{
cout << cnt1 << "---Hello, World!---" << cnt2 << endl;
}
}
errors in your version:
1) You cannot include header-files of standard-library in function-scope (and your include was not properly ended, you forgot '>' symbol).
2) When you declare variables in loop type should be pointed only before first.
I'm working through a demo program written by someone else, and I'm very confused about some of the statements they are using. I'm not very familiar with C++ (moreso with Obj-C) and I'm not sure if this is valid code or not. Take, for example, the following: (comments are mine)
int main(int argv, char** argc)
{
int perm [20]; //OK, so declare an array of ints, size = 20
for (int i=0; i < 20; i++)
perm = i; //whaaaaa??? thought you need to specify an element to assign to an array...
}
That is one example - my compiler throws an "incompatible types in assignment of 'int' to 'int [20]' error, but apparently others have been able to compile the program. Am I nuts, or is this bad code?
Here's another piece I just don't get:
int d[20] = {0}; //OK, another int array of size 20, initialized to 0's
for (int i = 1; i < n; i++)
{
d = d[i - 1]; //this I don't get - assign the array to one of its own elements??
if (invperm[i - 1] < b)
d++; //this would just increment to the next element?
}
I suspect the error is one of comprehension on my part, as if the code was bad other people would've commented on that fact...if anyone has a good explanation and/or resource I can read to understand this, I would be most appreciative!
Thanks!
*EDITED TO ADD*
In response to the answers below, I did copy/paste that code, and it looks intact to me...I can only assume when the original author posted it, it mangled it somehow. Thanks for the replies, I'm glad I had the right understanding, and I'll try and contact the author to see if there is an un-mangled copy out there somewhere!
All those examples are absolutely wrong. It looks like you lost [i] when you copied the code from wherever you got it from.
I have seen something similar with code sent over messenger programs that treat certain bits of text as emotes and replace them with images that don't get copied as text, but instead get dropped.
Your understanding is fine, that code is just entirely nonsensical.
d++; //this would just increment to the next element?
It would if d were a pointer. However since d is an array, it's simply illegal.
This is most certainly a copy/paste error.
I have succumbed to the temptation of copy/pasting code at one point during a game tech project involving Lua scripts. If the Lua script fails there is no feedback/output that indicates something is failed (which is very frustrating). After debugging for hours I realised my script was using 'smart quotes'.
Whilst this code is broken it can still teach you some things about C++.
int perm [20];
cout << endl << perm << endl;
cout << endl << &perm[0] << endl;
'perm' returns the memory address of the first element of the array. so when you are trying to assign 'i' to 'perm' in that main for loop (20 times) you will know now that you were trying to assign an integer to a memory address, hence the incompatible type error.
The second section however is verry broken and I can't discern much learning from this :P.
I added in an example program to show how pointers/arrays can be used:
#include <iostream>
using namespace std;
int main()
{
int d[20] = {0}; // 20 ints, set to 0
int * ptr = d; // points to d[0]'s memory address
for(int i = 0; i < 20; i++)
{
d[i] = 0 + i; // set array values
}
for(int i = 0; i < 20; i++)
{
// iterates through d and prints each int
cout << endl << "d[i]: " << d[i] << endl;
// dereferences the ptr to get the same int
// then incraments the position of the pointer for next time
cout << endl << "*ptr++: " << *ptr++ << endl;
}
getchar();
return(0);
}