Sean Ryan
Sean Ryan

Reputation: 37

My c++ program is printing out an address instead of a value

I have a c++ program that reads in a matrix from a file. It stores all non zero values and values above a threshold in a 2d vector of the structure I created. The structure holds the value and the index of that value. When I print out all of the values in the 2d vector it prints out the index but then it prints out what looks like an address for the value.

Here is the code itself:

#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <vector>
#include <math.h>

struct NZ{
  int index;
  double val;
} nz;

using namespace std;

int main(int argc, const char* argv[]) {  
    string line;
    int nonzero = 0;
    int rowNum = 0;
    double epsilon;
    bool ep = false;
    if (argc > 1 && string(argv[1]) == "-e")
    {
    epsilon = fabs(strtod(argv[2], 0));
    ep = true;
    }
    vector< vector<NZ> > rows;
    int linenum = -1;
    while (getline(cin, line))
    {
        rowNum++;
        rows.push_back( vector<NZ>() );
        std::istringstream lstream(line) ;
        double val;
        linenum++;
        int i = 1;
        while (lstream>> val)
        {
            if(ep == true)
            {
                if (val != 0 && fabs(val) > epsilon){
                nonzero++;
                nz.val = val;
                nz.index = i;
                rows[linenum].push_back(nz); 
            }
            }
            else if (val != 0){
                nonzero++;
                nz.val = val;
                nz.index = i;
                rows[linenum].push_back(nz); 
            }
                i++;
        }
    }
    cout << rowNum << " " << nonzero;
    for(int i=0; i<rows.size(); i++) {
        cout << endl;
        for(int j = 0;j<2;j++) {
            cout<< rows[i][j].index << " " << cout<< rows[i][j].val;
        }
    }
} 

This is the input file:

0 -0.25 3 4
1 0.2 0.2 5
4 0 2 0.1

This is what it outputs:

3 6
3 0x60626834 0x6062684
1 0x60626814 0x6062685
1 0x60626843 0x6062682

This is what it should output:

3 6
3 3 4 4
1 1 4 5
1 4 3 2

The first line prints out the number of rows in the file and the number of non zero numbers in the file. The rest of the lines print out the 2d vector. It first prints the index of the number and then the number itself.

Upvotes: 0

Views: 1274

Answers (1)

LBes
LBes

Reputation: 3456

Try to remove cout from this line:

cout<< rows[i][j].index << " " << cout<< rows[i][j].val;

To get

cout<< rows[i][j].index << " " << rows[i][j].val;

Upvotes: 1

Related Questions