So, I'm getting the above error (in the title) but for some reason it's only throwing this error on the second loop. Notice the first and second loop I have using the customer variable works absolutely fine, no errors thrown or anything. But on that last loop, the output[customer][charge] array, there is a red line under output[customer] that says "Subscripted value is not an array, pointer or vector". I am using xcode, Mavericks OSX. All of my arrays are defined elsewhere, and have worked perfectly the whole length of the program until now. There are some other operations going on in the program, but they have nothing to do with this loop, so I just posted the code that was giving the error. Again I'll say, the charges[customer][month][charge] loop works fine, but the output[customer][output] is not working.
P.S. You probably will think the logic behind keeping all this data in numerically indexed arrays is dumb, but it is for a school project. So don't lecture me about how this program is logically inconsistent or whatever. Thanks!
string headings[3][7];
string chargeLabels[3] = {"Electricity :","Water: ","Gas: "};
string outputLabels[5] = {"Subtotal: ","Discount: ","Subtotal: ","Tax: ","Total: "};
double charges[3][3][3];
double output[3][5];
for(int customer=0; customer<3; customer++)
{
for(int heading=0; heading<5; heading++)
{
cout << headings[customer][heading];
}
for(int month=0; month<3; month++)
{
cout << chargeLabels[month];
for(int charge=0; charge<3; charge++)
{
cout << charges[customer][month][charge] << ", ";
}
cout << endl;
}
for(int output=0; output<5; output++)
{
cout << outputLabels[output];
//error is below this comment
cout << output[customer][output] << endl;
}
}
Inside the for statement:
for(int output=0; output<5; output++)
{
You declared another variable int output which shadows the double output[3][5] with the same name outside the for statement.
Here's your problem:
double output[3][5];
for(int output=0; output<5; output++)
You're reusing output as a variable name twice.
So when you try to access it here:
cout << output[customer][output] << endl;
You're accessing the local output, which is just an int.
Related
Up until now I've been studying C, and now i wanted to try C++. Started out with some easy tasks. But I can't seem to find the answer, why is there a number either 0 or 488834... printed out.
I've tried re-declaring variables, using
for(n-1; n>=0; n--){
cout << a[n] << endl;
}
int main(){
int var = 0;
int a[100],n;
cin >> n;
for(int i=0; i<n; i++){
cin >> a[i];
var++;
}
for(var-1; var>=0; var--){
cout << a[var] << endl;
}
Everything works, except that 0/some number in the middle of the output
Result
In the following line:
for(var-1; var>=0; var--){
var-1 doesn't actually modify the value of var. So var gets to keep its original value, which means the first value you end up printing is what is after the end of the original sequence.
Use var = var - 1 instead.
In your second for loop you don't have an assignment, just a statement. You start printing from a location of the array that contains an invalid number due to this, you may want too have your second loop read
for(var = var-1; var>=0; var--){
cout << a[var] << endl;
}
Now, there are more element ways to write this, but this is a fix that is needed in your code.
I have finished writing a program that included reversing, expanding and shifting arrays using the pointer requirement asked by the professor. Everything compiles but the answer from the expand function does not return what I wish: adding 0s after the old user input array which asks for the size of the array and the numbers you wish to put into the array. I think my problem may lie from the fact that I include a pointer on something that might not have a reference in the program. Below is my code:
// *numPtr refers to my old user input array and int tamaño is the size of the array
void expandArray(int *numPtr, int tamaño) {
int *nuevoArray = new int[tamaño *2];
for (int i = 0; i<tamaño; i++) {
nuevoArray[i] = numPtr[i];
}
for (int i = tamaño; i < (tamaño*2); i++) {
nuevoArray[i] = 0;
}
std::cout << nuevoArray << " ";
}
As I said, my theory of the code not compiling the way I wish is because I use the *nuevoArray and it has no reference in my main code, but then again, I am just a beginner with C++. I was thinking of just doing a vector, but I think I would not follow the pointer requirements placed by the professor.
If you want to print the contents of nuevoarray, just use a for loop like this:
for (int i = 0; i < (tamaño*2); i++) {
std::cout << nuevoArray[i] << " ";
}
std::cout << "\n";
Also, since you are using new[] to create the array, you should not forget to delete[] it!
you can print your array by using
for (int i = 0 ; i < tamano * 2 ; ++i) {
std::cout << nuevoArray[i] << " ";
}
std::cout << std::endl;
or in c++11
for (auto i : nuevoArray) {
std::cout << i << " ";
}
std::cout << std::endl;
PS: The std::endl will return to the start of the new line and flush the cout buffer.
Your code does appear to be allocating a larger array and correctly copying data from numPtr into the new array and also correctly filling the remainder of the new array with zeros.
You don't explicitly say what you expect this function to output, but I'm guessing you expect it to print out the contents of the new array, and that you believe there's a problem because instead of that, you're seeing it print something like "0x7fb46be05d10".
You're not correctly printing the array out. Instead you're printing the memory address of the first element out. If you want to see the contents, then you need to loop over the elements of the array and print each one out individually.
Here's a function showing one way of doing that:
#include <algorithm>
#include <iterator>
void printArray(int *arr, int n) {
std::copy(arr, arr + n, std::ostream_iterator<int>(std::cout, " "));
}
Now you can replace the line std::cout << nuevoArray << " "; in your existing code with printArray(nuevoArray, tamaño*2);
(Also it sounds like whoever is teaching you C++ should take a look at this presentation from the recent C++ conference, CppCon 2015: Stop Teaching C)
I am basically trying to store everything after a certain index in the array.
For example, I want to store a name which is declared as char name[10]. If the user inputs in say 15 characters, it will ignore the first five characters and store the rest in the char array, however, my program crashes.
This is my code
char name[10];
cout<< "Starting position:" << endl;
cin >> startPos;
for(int i= startPos; i< startPos+10; i++)
{
cout << i << endl; // THIS WORKS
cout << i-startPos << endl; // THIS WORKS
name[i-startPos] = name[i]; // THIS CRASHES
}
For example, if my name was McStevesonse, I want the program to just store everything from the 3rd position, so the end result is Stevesonse
I would really appreciate it if someone could help me fix this crash.
Thanks
Suppose i is equal to 3. In the last iteration of the loop, i is now equal to 12, so substituting 12 in for i, your last line reads
name[12-startPos] = name[12];
name[12] is out of bounds of the array. Based on what you have shown so far, there is nothing but garbage stored in name anyway before you start doing this assignment, so all you're doing is reorganizing garbage in the array.
Please in future: post full compilable example.
A simple answer is that your array maybe is out of bound, since you don't provide full example its hard to know exactly.
Here is a working example:
#include <iostream>
using namespace std;
int main() {
int new_length, startPos;
int length = 15;
char name[15]= "McStevesonse";
cout<< "Starting position:" << endl;
cin >> startPos;
if(new_length <1){ // you need to check for negative or zero value!!!
cout << "max starting point is " <<length-1 << endl;
return -1;
}
new_length=length-startPos;
char newname[new_length];
for(int i= 0; i<new_length; i++){
newname[i] = name[i+startPos]; // THIS CRASHES
}
cout << "old name: " << name << " new name: " << newname << endl;
return 0 ;
}
To put it simply, change this:
for(int i= startPos; i< startPos+10; i++)
To this:
for(int i= startPos; i<10; i++)
You should be fine with that.
Explanation:
At some point, when you use the your old loop, this name[i-startPos] = name[i] would eventually reach an array index out of bounds and causes the crash.
Don't forget to clean up/hide the garbage:
Doing so, would cause the output to produce some kind of garbage outputs. If you got a character array of 'ABCDEFGHIJ', and have chosen 3 as the starting position, the array would be arranged to 'DEFGHIJHIJ'. In your output, you should atleast hide the excess characters, or remove by placing \0's
I wrote the following code to test in int main()
int main() {
int *p1 = findmatrixsize("inputmatrix.txt","A");//A function gets matrix size
cout << p1[0] << endl << p1[1] << endl;
int *p2 = findmatrixsize("inputmatrix.txt","B");
cout << p2[0] << endl << p2[1] << endl;
double **C = normalmultiplication("inputmatrix.txt","A", "B");
cout << C[0][0] << endl;
ofstream fout;
const string s="outputmatrix.txt";
fout.open(s);
for(int i=0;i<p1[0];i++){
for(int j =0;j<p2[1];j++){
fout << C[i][j] << " ";
}
fout<< endl;
}
fout.close();
return 0;
}
Everything works except when I am executing the multiarray printing. Here is the problem:
1.If I comment out the printing part, p1[0],p1[1],p2[0],p2[1],C[i][j] gives me perfect and correct result that I want.
2.However, when I print by using normal loops it doesn't work. But, but,but, if I change the p1[0],p2[1] in the for loop to a concrete number like 3(when my matrix dimension is 3), it works again.
3.It compiles, but the for loop printing part is not written into the txt. When I changed it to the standard print cout(not only the single line, I mean the whole method), I couldn't see them in the terminal neither. But as I mentioned above, when I change p[0] p[1] to 3, it works, which means I can see them either in the txt or terminal
I have never met such weird situation in C++ before, so I hope someone can help me out!
FYI, I use Visual Studio 2010 as compiler.
Thanks for your help!
We don't know what findmatrixsize and normalmultiplication do.
But if they do what I think they do (and I think they return pointers to their local data), the objects referred to by p1, p2 and C share storage.
Check if p1 == p2.
The problem is in the way you get result from findmatrixsize and normalmultiplication functions: they keep the result of calculation in stack and return a pointer to it, but the stack is destroyed soon after these functions finish their work. Reimplement these functions so that the place in memory is valid outside of these functions. For example,
int p1[2];
findmatrixsize("inputmatrix.txt","A", p1)
and put the result inside of findmatrixsize into the last argument, eg.
void findmatrixsize(const char* fileName, const char* matrixName, int* result)
{
// routine
result[0] = someValue1;
result[1] = someValue2;
}
I am newbie to programming and I am trying to pass an array into a function and add all the elements together and return the sum. The problem is that I am getting a garbage value for the sum. I have researched on how to pass arrays to functions and I do not know if I'm supposed to use a pointer to pass arrays. I am not good with pointers anyways.
Here is my code
#include <cmath>
#include <cstdlib>
using namespace std;
float mean(int);
int sum(int ARRZO[5]);
int total;
int main()
{
int ARRZ[5];
char *inname = "example.txt";
ifstream infile(inname);
if (!infile) {
cout << "There was a problem opening file " << inname << " for reading." << endl;
return 0;
}
cout << "Opened " << inname << " for reading." << endl;
for(int i=0; i<11; i++)
{
while (infile >> ARRZ[i])
{
cout << "Value from file is " << ARRZ[i] << endl;
}
}
total=sum(ARRZ);
cout<<"the sum of the elements in the array is"<<total<<endl;
system("PAUSE");
return 0;
}
int sum(int ARRZO[])
{
int sumz=0;
for (int i=0; i<5; i++)
{
sumz+=ARRZO[i];
cout<<ARRZO[i];
}
cout<<sumz<<endl;
return sumz;
}
You are actually reading all the values from the file in ARRZ[0] because of the inner loop. By the time you get to i=1, you are at the end of the file, and not reading anything.
Remove one loop, and increment i when you have read successfully a value.
I'm not sure what you think this pair of nested loops is supposed to do:
for(int i=0; i<11; i++)
{
while (infile >> ARRZ[i])
{
cout << "Value from file is " << ARRZ[i] << endl;
}
}
But (as #aliexisdm pointed out) the inner loop reads the entire content of the file. What he didn't (at least directly) point out is that you're reading every one of those values into the first element of your array. Then you're getting back to the outer loop, incrementing i, and trying to read the file again -- but since the stream's failbit has been set, all your subsequent attempts at reading are guaranteed to fail.
After that, you add up the 5 items in the array, but since you haven't read anything into 4 of them (and never initialized its contents) you end up with the last item you read from the file + 4 garbage values, giving still further garbage as the result (well, usually anyway -- you really have undefined behavior, so the program could crash and burn instead, but with most current computers, you'll just get some meaningless number).
I, however, would advise changing the program a bit more than just removing one loop and incrementing in the loop that's left. Instead, I'd remove all the (explicit) loops, and make some attempt at making real use of what the standard library provides.
You can read the numbers from the file in one fell swoop:
std::ifstream infile(inname);
std::vector<int> ARRZ ((std::istream_iterator<int>(infile)),
std::istream_iterator<int>());
Then you can sum them all with std::accumulate:
int sum = std::accumulate(ARRZ.begin(), ARRZ.end(), 0);
Finally, you can print out the result:
cout << "The sum of the elements in the array is: " << sum << "\n";
Since, however, you only read the values from the file to add them together, you don't really need to store them at all. You could just add them together and print out the result:
cout << "The sum of the elements in the file is: "
<< std::accumulate(std::istream_iterator<int>(infile),
std::istream_iterator<int>(), 0);
The whole job reduced to one step...