Errors trying to compile a simple code

  • C/C++
  • Thread starter member 428835
  • Start date
  • Tags
    Code Errors
In summary: When trying to compile the following c++ code I get the errors I've screenshotIn summary, when trying to compile the following code I get the errors I've screenshot.
  • #1
member 428835
When trying to compile the following c++ code I get the errors I've screenshot
C++:
// p12
#include <iostream>
#include <vector>
#include <string>
#include <map>
class Solution {
private:
    std::vector<int> num = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
    std::vector<std::string> sym = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
    int i = sym.size();
    std::string result = "";
public:
    std::string intToRoman(int number) {
        while(number>0)
        {
        int div = number/num[i];
        number = number%num[i];
        while(div--)
        {
            result += sym[i];
        }
        i--;
        }
    return result;
    }
};
int main()
{
    int num_ = 58;
    Solution ob1;
    auto sol = ob1.intToRoman(num_);
    std::cout << sol << "\n";
    // Solution* ptr;// = &ob1;
    // ptr = &ob1;
    // int a = ptr->intToRoman(num_);
    // std::cout << a << "\n";
    // std::shared_ptr<Solution> ptr2 = std::make_shared<Solution>();
    // int b = ptr2->intToRoman(num_);
    // std::cout << b << "\n";
    return 0;
}
. I'm using mac VS code, and you can see I've turned on c++11. Not sure what the issue is; any suggestions?

cpp11 turned on (I think):
Screen Shot 2022-12-04 at 11.19.36 AM.png

errors:
Screen Shot 2022-12-04 at 11.19.06 AM.png
 
Technology news on Phys.org
  • #2
It looks like you are trying to initialize the vector num in line 9 using the syntax for initializing an array.
Try num{1, 4, .....,1000};
CORRECTION: It looks like C++ 11 should allow the "num = {" syntax.
 
Last edited:
  • #3
At a glance your initialization look like valid C++11 to me, but considering all the warnings complaining about the code using C++11 features I would think you are not really compiling with C++11.
 
  • Like
Likes FactChecker
  • #4
Filip Larsen said:
At a glance your initialization look like valid C++11 to me, but considering all the warnings complaining about the code using C++11 features I would think you are not really compiling with C++11.
So should I just uninstall and reinstall VS code?
 
  • #5
I get a runtime error (Debug assertion failed) when I attempted to run your code. The problem seems to be in how i is defined. The private data member i is set to 13, the number of elements in the sym vector. First off, i is a very bad choice for the name of this variable. Single-letter identifiers such as i, j, and k should be used only as loop control variables and/or as array indexes. They should not be used to denote the size of an array.
Your intToRoman() method needs to define its own index variable. I don't understand your algorithm well enough to make any suggestion, other than you probably need a loop that goes through the sym vector.

BTW, I ran your code through my VS 2017 compiler. I will probably update to VS 2022 sometime soon, but haven't done it yet.

C++:
int i = sym.size();
<snip>
 std::string intToRoman(int number) {
        while(number>0)
        {
        int div = number/num[i];[/icode]
 
  • #6
Update:
The reason I was getting a runtime error was that the code was trying to access elements beyond the end of the vector. At the start of the program, i was set to the size of the sym vector, or 14. The problem is that these vectors don't have elements at index 14.

Here was my fix, changing the index from i to i - 1:
C++:
std::string intToRoman(int number) {
        while(number>0)
        {
        int div = number/num[i - 1];
        number = number%num[i - 1];
        while(div--)
        {
            result += sym[i - 1];
        }
In your main() function num_ was set to 58. My version produced output of LVIII, the correct result.
 
  • #7
joshmccraney said:
So should I just uninstall and reinstall VS code?
I haven't used VS code in ages (I use MS VS), but I would imagine that it is missing some configuration or component. If you are just doing this for code exercises you can alternatively try an online compiler instead, like onlinegdb.com or https://godbolt.org.
 
  • #8
Let me reiterate my advice to take a class. You say you can't. I find that hard to believe, with community college satellite campuses and web-based instruction popping up like mushrooms. Heck, my park district and library both have classes! But the real reason is this isn't helping. The strategy of cobbling something together, asking us, arguing with us for a bit, eventually getting past it and repeating has not improved your code. You are still struggling with things at the beginning.

Now, let me reiterate the point @Mark44 made. i is a very bad choice for variable name. There was a time when variables were limited to single letters (and by extension, only 26 were allowed in a program) and these were not happy times. You're asking for help. Show some respect and make it easy for people to help you. Two of the most most important aspects of that are using intelligent and intelligible variable names, and to post the minimum code needed to produce the error.

Now your problem is very, very simple. It has nothing to do with C++11 and nothing to do with your IDE, It is one of the most basic things: your array is not indexed 1 to 13; it's indexed 0 to 12. Asking for array element 13 is out of bounds.
 
  • #9
I believe you have set the C++ standard only for VSCode's intellisense, which is for syntax highlighting and code completion while editing.
The compiler itself still uses the wrong C++ standard. You can check by inspecting the compile commands in the terminal window. It should contain something like -std=c++11 if it is set correctly. That is probably missing at the moment.
 
Last edited:
  • #10
Okay, still having issues, so maybe I won't compile from VS. So I make the run.sh file which looks like this:
Code:
#! /usr/bin/env bash

g++ -std=c++11 -o ./curr ./curr.cpp
./curr

where curr.cpp is here:

C++:
// p12
#include <iostream>
#include <vector>
#include <string>
#include <map>
class Solution {
private:
    std::vector<int> num = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
    std::vector<std::string> sym = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
    int i = sym.size();
    std::string result = "";
public:
    std::string intToRoman(int number) {
        while(number>0)
        {
        int div = number/num[i];
        number = number%num[i];
        while(div--)
        {
            result += sym[i];
        }
        i--;
        }
    return result;
    }
};
int main()
{
    int num_ = 58;
    Solution ob1;
    auto sol = ob1.intToRoman(num_);
    std::cout << sol << "\n";
    // Solution* ptr;// = &ob1;
    // ptr = &ob1;
    // int a = ptr->intToRoman(num_);
    // std::cout << a << "\n";
    // std::shared_ptr<Solution> ptr2 = std::make_shared<Solution>();
    // int b = ptr2->intToRoman(num_);
    // std::cout << b << "\n";
    return 0;
}
but when I execute run.sh in terminal I get the output:
Screen Shot 2022-12-04 at 4.51.05 PM.png


My json file is here:
Screen Shot 2022-12-04 at 4.48.18 PM.png
 
  • #11
The errors indicate that you are still using the wrong C++ standard.
So the command line that you intended does not seem to be executed.

How about typing the compile command in an actual linux shell and not use VSCode at all?
Also note that your shell script as it is now, will compile, and regardless of the result, will still run the executable.
 
  • #12
If I compile your code with the command that is in your shell script, it compiles correctly without output, and I can run it, although I get a run time exception:
C++:
g++ -std=c++11 -o ./curr ./curr.cpp
./curr
Floating point exception (core dumped)
If I compile it with an older standard, I get what you have:
C++:
g++ -std=c++98 -o ./curr ./curr.cpp
./curr.cpp:8:79: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
   std::vector<int> num = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
...
 
  • #13
joshmccraney said:
Okay, still having issues,
It looks like you didn't make the changes I gave in post #6, that V50 notes i the quoted text below.
Vanadium 50 said:
Now your problem is very, very simple. It has nothing to do with C++11 and nothing to do with your IDE, It is one of the most basic things: your array is not indexed 1 to 13; it's indexed 0 to 12. Asking for array element 13 is out of bounds.
BTW, the arrays have 14 elements in them, not 13, but the point he made is apt.
I like Serena said:
it compiles correctly without output, and I can run it, although I get a run time exception:
Which I mentioned in posts 5 and 6.
 
Last edited:
  • #14
Whoops. My counting is one off. I have problems with more than ten. :smile:

🖐🖐
 
  • #15
Vanadium 50 said:
Whoops. My counting is one off. I have problems with more than ten. :smile:

🖐🖐
I count 13.
?????

Btw, I executed the original code unaltered in Xcode and it didn't have a problem.
I found this a bit peculiar after I added a line of code after line 16 to check something and it seems to have no problem dividing by zero.

Xcode can divide by zero 2022-12-04 at 14.34.44.png
 
  • #16
Vanadium 50 said:
Whoops. My counting is one off.
Gulp! Actually, my count was off. VS gave the value of i as 0x000000c (approx. nu. of zeroes). I erred in mentally converting this hex number to decimal.

OTOH, maybe I was counting XIV, which isn't actually present. o0)
OmCheeto said:
I count 13.
Right. I have edited my earlier post. Still, if you have an array with 13 elements, you should not try to access the element at index 13, at least not in C or related programming languages.
 
  • Like
Likes member 428835
  • #17
Mark44 said:
Gulp! Actually, my count was off.
That'll teach me to trust you! :wink: Next time I'm taking off my socks and counting myself! 🧦

This reinforces points made earlier in this and other threads. "i" is a terrible name, since it's not obvious from the name that it's one more than the maximum index. The mistake is in Line 10, but the error doesn't occur until Line 16.
 
  • #18
Mark44 said:
Gulp! Actually, my count was off. VS gave the value of i as 0x000000c (approx. nu. of zeroes). I erred in mentally converting this hex number to decimal.

OTOH, maybe I was counting XIV, which isn't actually present. o0)

Right. I have edited my earlier post. Still, if you have an array with 13 elements, you should not try to access the element at index 13, at least not in C or related programming languages.
Totally missed the initial comment, sorry! But I'm STILL having issues:
Screenshot 2022-12-05 at 6.58.27 PM.png
I googled the first error but had no clue what to do, since results led me to -Weverything commands, which I'm not using. I thought I selected c++11, as shown. Any ideas? Thanks so much for all the help!
 
  • #19
joshmccraney said:
I googled the first error but had no clue what to do
Nothing in the screen shot you posted is an error. These are all warnings. When the compiler reports an error, it doesn't produce an executable. With warnings, it should produce an executable, as long as you don't have the compiler configured to treat warnings as equivalent to errors. I don't have the same VS version as you are using, but I'm sure there's a way to adjust the settings for warning levels, likely under Project-><Project Name>Properties ->Configuration Properties -> C/C++ -> General. One of the options here is Warning Level, and another is Treat Warnings as Errors.

The first warning has to do with where you have told the compiler to look for include files. The warning is that for some reason the compiler deems this as an unsafe location. I'd be tempted to let that one slide.

Several more warnings have to do with how you are initializing the two vectors. I would look up how vectors should be initialized.

A couple of the warnings have to do with possible loss of precision in converting from unsigned long to int. This is caused by your use of the size operator. You could eliminate that warning by changing the type of the variable from int to unsigned long, or you could use a cast to convert to an int.

Are you able to run your program? If so, you're going to get a runtime error unless you've made the changes that are recommended in this thread.

The two config options you showed are for C11 (C/C++ config) and C++11 (C ++ standard). Most of the warnings have to do with C++98, an older standard.
 
  • Informative
Likes berkeman
  • #20
Mark44 said:
Nothing in the screen shot you posted is an error. These are all warnings. When the compiler reports an error, it doesn't produce an executable. With warnings, it should produce an executable, as long as you don't have the compiler configured to treat warnings as equivalent to errors. I don't have the same VS version as you are using, but I'm sure there's a way to adjust the settings for warning levels, likely under Project-><Project Name>Properties ->Configuration Properties -> C/C++ -> General. One of the options here is Warning Level, and another is Treat Warnings as Errors.

The first warning has to do with where you have told the compiler to look for include files. The warning is that for some reason the compiler deems this as an unsafe location. I'd be tempted to let that one slide.

Several more warnings have to do with how you are initializing the two vectors. I would look up how vectors should be initialized.

A couple of the warnings have to do with possible loss of precision in converting from unsigned long to int. This is caused by your use of the size operator. You could eliminate that warning by changing the type of the variable from int to unsigned long, or you could use a cast to convert to an int.

Are you able to run your program? If so, you're going to get a runtime error unless you've made the changes that are recommended in this thread.

The two config options you showed are for C11 (C/C++ config) and C++11 (C ++ standard). Most of the warnings have to do with C++98, an older standard.
I think the vectors don't like being initialized because it's using c++98 and not 11. When I run this on an online compiler I get the solution and no warnings (here I don't even get a solution) (my last error I did not show, but this error has to do with again the c++98 and not 11). I'm pretty confused.

Do you know a way for me to reset the settings? I've already deleted and reinstalled VS code, but no help. Is there a way to delete the compiler and reinstall? Is this even safe? Thanks for your help!
 
  • #21
joshmccraney said:
I think the vectors don't like being initialized because it's using c++98 and not 11.
If you can turn these off completely, that might help. Again, what you were seeing is warnings, so take a look at what I said in my previous post about setting or adjusting the warning levels. Below, I've provided a link to some documentation videos that you should look at.
joshmccraney said:
When I run this on an online compiler I get the solution and no warnings
The "solution" in VS parlance is the files you see in the VS user interface. Are you able to get an executable -- a complete program that you can run?

You said you're using VS Code, but I don't know anything about this version. I would strongly advise checking out the documentation for this product -- see https://code.visualstudio.com/docs
Look at the section titled "First Steps," especially the Intro Videos, and the ones about Setup, UI, and Settings.
joshmccraney said:
Do you know a way for me to reset the settings? I've already deleted and reinstalled VS code, but no help. Is there a way to delete the compiler and reinstall? Is this even safe?
Since you're running on a Mac, I haven't done anything on a Mac for about 25 years, so you're on your own. There ought to be a way to uninstall programs that you've installed, though. I don't see why uninstalling a program would be unsafe, provided that you use whatever Macs have to do it. You wouldn't want to just go in and delete files willy nilly. On Windows computers, installers will usually make changes in the Registry, but Macs are a different animal altogether.
 
  • Like
Likes member 428835
  • #22
Does your IDE have a manual?
 
  • #23
Thanks for all your help! Sadly when I try to execute
Code:
#! /usr/bin/env bash

g++ -std=c++11 -o ./curr ./curr.cpp
./curr
from the terminal I still get the errors I pointed out above. Might just switch to Linux because this is getting ridiculous. Thanks though!
 

What is a compilation error?

A compilation error is an error that occurs when a program is being compiled, or translated from its human-readable form into machine code. This can occur for a variety of reasons, such as syntax errors, type mismatches, or missing dependencies.

Why am I getting a compilation error?

There are many potential reasons why a compilation error might occur. Some common causes include typos or syntax errors in the code, missing or incorrect library dependencies, or incompatible versions of software being used.

How can I fix a compilation error?

The steps to fix a compilation error will depend on the specific error message and the language or software being used. In general, carefully reviewing the error message and checking for any mistakes in the code or dependencies is a good first step. If necessary, consulting documentation or seeking help from others can also be helpful.

Can a compilation error be ignored?

In most cases, compilation errors should not be ignored. They indicate that there is a problem with the code that needs to be fixed in order for the program to run correctly. Ignoring a compilation error can result in the program not functioning as intended or even crashing.

How can I prevent compilation errors in the future?

To prevent compilation errors, it is important to pay close attention to coding conventions and syntax rules, as well as thoroughly testing the code before attempting to compile. Keeping software and dependencies up-to-date can also help to avoid compatibility issues that can lead to compilation errors.

Similar threads

  • Programming and Computer Science
Replies
1
Views
990
  • Programming and Computer Science
Replies
13
Views
2K
  • Programming and Computer Science
Replies
1
Views
876
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
10
Views
1K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
2
Replies
36
Views
3K
  • Programming and Computer Science
4
Replies
118
Views
6K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
2
Replies
39
Views
3K
Back
Top