我的c++程序正在打印一个地址而不是一个值

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

本文关键字:一个 地址 c++ 我的 程序 打印      更新时间:2023-10-16

我有一个c++程序,可以从文件中读取矩阵。它将所有非零值和阈值以上的值存储在我创建的结构的2d向量中。该结构包含该值和该值的索引。当我打印出2d向量中的所有值时,它会打印出索引,但随后它会打印出来该值的地址。

这是代码本身:

#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;
        }
    }
} 

这是输入文件:

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

这就是它的输出:

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

这是它应该输出的:

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

第一行打印出文件中的行数和文件中非零数字的数目。其余的行打印出二维矢量。它首先打印数字的索引,然后打印数字本身。

尝试从此行删除cout

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

获取

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