I use Visual C++ 2010 Express Edition to compile and run the .exe files I write in the C++ programming language. I am trying to create a loop-based logic using C++ to ask the user how many entries he chooses to enter, and ask questions limited to that no. of entries. For example I want to output, "How many characters do you wish to enter?: " Say the user gives the answer as '3' which is stored in the int variable 'entries'. I then want to keep asking the question 3 times before it stops and continues with the next line of code. I hope you understand, here is a block of code to demonstrate what I am doing:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How many values do you need to enter?: ";
int entries;
cin >> entries;
int offset, number;
string valueName[50];
float valueValue[50];
for (offset = 0; offset < entries; offset++)
{
cout << "Enter " << number << " Value Name: ";
cin >> valueName[offset];
cout << "Enter " << valueName[offset] << "\'s value: ";
cin >> valueValue[offset];
for (number = 1; number <= entries; number++)
{
}
}
char response;
cin >> response;
return 0;
}
Strangely when I run this simple program, it fails when I enter the value's name to be inserted into the 0th element of the valueName[] array. It just pauses the execution of the program and a dialog box pops up saying "Runtime Check Failure #3 - Variable 'number' is being used without being initialized!" Another problem regarding this program is that, for quite some time, when I ran this program this "Runtime Check Failure #3" box never appeared, and when it didn't, the number value went wrong, and first started with 1, and then for the next loop jumped to 6, and then repeated 6 again for the next loop! Please help me! I've checked online scouring this problem everywhere, but it just doesn't apply to my type of problem! Is it because the variables are out of scope? But they're declared outside the for loops right? So please help me!
The runtime is telling you the truth, the following line comes after you have declared number as an int but have not given it a value.
cout << "Enter " << number << " Value Name: ";
In your code you declare the following, in C++ this means give me 2 ints but the values are not defined yet, e.g.
int offset, number;
Change it to something like this ..
int offset = 0;
int number = 0;
You are printing the variable number without assigning to it first, i.e. it's uninitialized. When it prints some random number it's because that what happens to be in the memory at the time you run the program. Assign a value to it before you use it.
The problem is exactly the error message you're getting. You're using the variable number without initializing it.
You use the variable right here, at the top of your loop, when it hasn't been initialized to anything yet:
cout << "Enter " << number << " Value Name: ";
What is your intention with the number variable? It doesn't really seem to be serving any purpose. If you want to print which entry you're currently on, you could use the offset variable instead, like this:
cout << "Enter " << offset << " Value Name: ";
But that still seems a little unclear to me.
But the reason that you're having a problem is because the value is uninitialized, so you're experiencing undefined behavior. This is also the reason that Visual Studio doesn't always catch it; it will probably always catch in Debug mode, but in Release mode it will almost never catch it. You need to initialize all your variables before you use them.
In my case it was because an extern variable was declared twice.
Related
This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
Closed 2 years ago.
I'm a newbie in the programming world, and i've decided to start with C++ code a few days ago as my first programming language.
I just started to read an online course which i'm guiding on (and aply while i'm reading it).
The course in question assigns a serie of small optional exercises, wich go hand in hand with the topic that is being dealt at that moment.
One of this optional exercises is: "Create a program that multiplies two whole numbers in the following way: it will ask the user for a first whole number. If the number that you type is 0, it will write on the screen "The product of 0 by any number is 0". If a number other than zero has been entered, the user will be prompted for a second number and the product of both will be displayed."
How it says, I did my best to coding that program.
The code of what I did is:
#include <iostream>
using namespace std;
int main ()
{
int a;
int b;
int solve;
cout << "Enter a number: ";
cin >> a;
if (a!=0)
{
cout << "Enter another number: ";
cin >> b;
}
if (b!=0)
{
solve = a * b;
cout << "The result of your operation is: " << solve << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
return 0;
}
So, I press F9 to compile, then F10 to run it.
I proceed to testing it.
I put and different number from zero, I put another one. Throws me a multiplication of both. Nice.
I put and different number from zero, I put another one that actually its zero. Throws me the message of "else" order. Nice.
**BUT
I put and number equal to zero, and throws me the message of the "cout" order of "if (b!=0)".**
I didn't really know what I had done wrong, so, I ask for help from a friend who has some more experience than me, and tells me that actually it's nothing wrong. In fact, he proved me sending to me a screen cap of his Dev C++ with my code in it, and how it runs just how it had to be.
Then, I opened an online compiler (https://www.onlinegdb.com/online_c++_compiler#) to get down my doubts, and yes, there runs correctly too.
So, here's my question?
What's the problem? Why that happens?
I have the DevC++ 5.11 TDM-GCC 4.9.2, and I'm using the deafult compiler.
Please, I would like some of help, I feel more comfortable compiling in PC than online, it's more quick.
Thank you anyway for reading until here.enter image description here
The reason why this happens, as #TrebledJ mentioned, is that you've not initialised the variable b. So you can get over this problem just by initialising b to any value of your choice (preferrably 1 or 0 for simplicity). But there's a workaround if you don't want to initialise the values. I would transform your code to something like this:
if (a!=0)
{
cout << "Enter another number: ";
cin >> b;
if (b!=0)
{
solve = a * b;
cout << "The result of your operation is: " << solve << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
Basically, what I'm doing is, if the value of a after input is 0, I'm not running the part for taking the user input of b.
I am confused after the following C++ code executed:
#include <iostream>
using namespace std;
int main()
{
char name[0];
int roll;
cout << "Enter your name: ";
cin.get(name, 30);
cout << "Enter roll no.: ";
cin >> roll;
cout << "You have entered:" << '\n';
cout << "Name: " << name << '\n' << "Roll No. " << roll << '\n';
return 0;
}
As you see, it simply takes input and print it. But the problem is, how cin is supposed to read all the characters i have entered if the value of array is 0!!!
The output is as follows:
Enter your name: Bharat Singh Chauhan
Enter roll no.: 12345
You have entered:
Name: Bharat Singh Chauhan
Roll No. 12345
Sorry if the question is asked before ;)
This code:
char name[0];
cin.get(name, 30);
invokes undefined behavior because name does not have enough space to store 30 chars. This means anything can happen, including the program appearing to work sometimes.
Instead, you can do:
std::string name;
std::cin >> name;
// or
std::getline(std::cin, name); // if you want to accept whitespace
which is less error prone in general than using arrays.
Because C/C++ doesn't check memory borders natively. It is undefined behavior, because you're overwriting memory that you didn't allocated here, so, probably, overwriting memory, that was allocated for another purpose, for another variables, structs, etc. With another conditions you can get segmentation failed error.
Why conditions for segmentation failed didn't met now? Because default stack size (memory where your variable is "allocated") is much larger by default and easily can handle your hand-types strings here.
Also compilers could have option stack protection. So, they will warn if you overrun stack memory. It will not really protect you from undefined behavior or overwriting your local variables, but can help to find the problem, not always, but when your overrun is large enough to detect it. See this link for more information: Stack smashing detected
char name[0]; - that is an array of zero 0 characters. If you read more than 0 characters into it, you have undefined behaviour. Arrays don't automatically grow as you add stuff to them. For that you want std::vector or std::string.
Introduction
I am trying to code a converter for bin/oct/dec/hex numbers in c++. At first I print a message in a console asking the user to insert the type of conversion he wants to do and, followed by the cin that allows him to enter the conversion and then i ask him for the number followed by the cin that allows him to enter the number.
My problem
My problem is that after the user inserts the conversion, the variable gets printed on the console without me telling it that.
What I've Tried
I looked on the docs and in their example they do it like this:
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
And that is similar to my code(which you will see below).
I also tried to do getline(cin, type) but still the variables would get printed without me coding that.
My code
Faulty code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string type;
int n;
cout << "Insert what type of conversion you want to make(binoct, bindec, binhex, octbin, octdec, octhex, decbin, decoct, dechex, hexbin, hexoct, hexdec): ";
cin >> type;
cout << "Insert the number you want to convert: ";
cin >> n;
return 0;
}
Input
binoct
1001
Output
Insert what type of conversion you want to make(binoct, bindec, binhex,octbin, octdec, octhex, decbin, decoct, dechex,hexbin, hexoct, hexdec):binoct
binoct
Insert the number you want to convert:1001
1001
Expected output:
Insert what type of conversion you want to make(binoct, bindec, binhex,octbin, octdec, octhex, decbin, decoct, dechex,hexbin, hexoct, hexdec):binoct
Insert the number you want to convert:1001
Additional notes
I should mention that before this version of the code I did use cout to print my variables to see if it works but i re-built the code a few times and now there's no cout << type or cout << n inside my code
I looked on stackoverflow and I didn't seem to see anything similar, if this is a duplicate I apologize.
The code is fine, either clean and rebuild your project, or it has something to do with your project / debug settings, that print out the value.
Try Building and Running the Program in release mode.
It seems like I always come here to ask silly questions, but here it goes. As of right now I am in my first compsci course and we are learning c++. I've had an extremely basic introduction to c before, so I had thought I'd go above and beyond my current assignment. Now I was doing this just to showboat, I felt like if I didn't practice my previous concepts they would eventually fade. Anyways, on to the problem! I was supposed to write some code that allowed the user to input their initials, and a series of exams. Now this was supposed to accomplish three things: average the exams, print out the entered exams, and print out their initials. Well, what was a simple assignment, got turned into a huge mess by yours truly.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string uInitials;
float avgExam = 0, tExam = 0;
int aExams[10] = {'0'};
int i, nExam = 0, cExam;
cout << "Enter your three initials!";
cin >> uInitials;
do
{
cout << "Enter your exam(s) to be averaged. Enter 0 when complete!\n";
cin >> cExam;
aExams[nExam] = cExam; //I used this before nExam was incremented, in order to get nExam while it was '0' That way the first exam score would be properly saved in the first space
nExam++;
tExam += cExam; //This is just to add all the exams up to later calculate the average
}
while(cExam != 0);
avgExam = tExam/(nExam - 1); //subtracted '1' from nExams to remove the sentinel value from calculations.
cout << "The average for initials: " << uInitials << " is: " << avgExam << endl;
cout << "This average was obtained using the following scores that were entered: \n";
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
return 0;
}
The previous is my code, and the problem is that I'm getting output errors where it adds two '0's when I print out the list of entered exams. Also I feel like I made the whole do{}while() loop one huge clunky mess, so I'd like to refine that as well. If anyone could assist this poor, ignorant, beginner I would greatly appreciate it. Thank you for your time!
Some advice that i can give is for example in the 5th line there is no need
to put the 0 between ' ' and not even need to use the assign = operator.
You can initialize the array like this:
int aExams[10]{0};
Which will initialize all elements to 0,but can't be used for other value.
For example you won't have all the elements with value 1 if you write
int aExams[10]{1};
If your intention to initialize all elements in an array is with value other than 0 you can use fill_n(); function.
fill_n(aExams, 10, 1);
The first argument is the name of the array, the second is up-to which element you want to be initialized with the third argument, and the third is the value you want all elements to have.
Do not leave uninitialized variables like in line 6 with cExam and i variables. Initialize it like cExam=0; (copy-assign initialization) or cExam(0); (direct initialization). The latter calls the constructor for int built-in type.
A negative i see in your do-while loop is that you do not make sure that the user will enter under 10 exams,bad things will happen if the user tries to input 15 exams in an array that can hold only 10.
Just change the while to something more like this:
while( cExam != 0 && (nExam<10) );
You can also write the first two lines of the do-while loop outside the loop.
It is needed only once to tell the user that to stop the loop he/she needs to enter 0. There is no need to tell them this on every iteration plus that you will have a good performance benefit if you put those two lines outside the loop.
Look here how i would write the code and ask if you have any questions.
http://pastebin.com/3BFzrk5C
The problem where it prints out two 0's at the end of your code is a result of the way you wrote your for loop.
Instead of:
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
Use:
for (i = 1; i < (nExam); i++)
{
cout << aExams[i - 1] << endl; //Used a for loop to prevent redundancy
}
I'm not sure how to title my question, but here goes. I am testing some features, and I have hit a snag.
What I want to know is how can I set up a "for" or "if" statement to only put values in an array that meet a criteria? For example, find every divisor for a number, but only put factors in an array.
Any help would be loved, source code can be provided if needed :). Yes, I am new, so be gentle!
#include <iostream>
using namespace std;
int main(){
int n;
int counter = 1;
cout << "What number would you like to use? ";
cin >> n;
int DiviArray[n];
for (int k=0,j=1;k<n;k++,j++)
{
DiviArray[k] = n-k;
}
int k = 3;
int factn[n];
cout << "Factors of " << n << ": " << endl;
for (int i=0, j=1;i<n;i++,j++)
{
factn[i] = n/DiviArray[i];
if(factn[i]*DiviArray[i]==n)
{
cout << counter << ". " << factn[i] << " x " << DiviArray[i] << endl;
counter++;
}
}
return 0;
}
EDIT: Decided to go with vectors, not sure if I can get it to work, but thanks for the feedback guys :)
Since you don't know in advance how many values will meet the condition, you should use a std::vector.
As a benefit, it keeps track of how many elements you've already added, so push_back will always use the next available index.
This also fixes
cin >> n;
int DiviArray[n];
which isn't legal C++.
If you only want to put the values into the array that match the condition, then you should only put a number into the array when the condition is matched. To do that, the statement that puts a number into the array has to be inside the if-block for the condition. I hope I don't need to explain why :)
This is the only time in your program where you actually do want two indices: one that is incremented every time through the loop (to count how many times to run the process), and one that is incremented only when you put a number in the array (to figure out where the next number goes). Everywhere else, you've created a completely useless j variable (the uselessness should be apparent from the fact that there is no code that actually uses the value, only code to set it).