简体   繁体   中英

Pausing for input C++

I'm trying to write some code that will allow the input of a matrix and then calculate the inverse of the matrix followed by the input for a vector. However once the matrix values have been entered I cannot get the code to pause and wait for the vector entries, it just executes the rest of the main filling the vector with zeroes by default. Is it possible to reset the input or something so that the console will wait for input when I want to fill the vector?

#include <iostream>
#include "MatrixInverse.h"
#include "ReadMatrixRow.h"
#include "GlobalMinVar.h"

using std::cin;
using std::cout;
using std::endl;

int main(){


    int i;
    int const n_size=3;
    double **SigmaInv, **Sigma,*mu,*MinVarWeight;

    Sigma = (double **)malloc(n_size * sizeof(double *));
    Sigma[0] = (double *)malloc(n_size * n_size * sizeof(double));
    for(i = 1; i < n_size; i++)
    { Sigma[i] = Sigma[0] + i * n_size;}

    cout<<"Enter the entries of the covariance matrix row by row,"<<endl;
    cout<<"breaking each row with a non-numeric character:"<<endl;

    //PAUSES HERE FOR MATRIX INPUT

    for (i=0;i<n_size;i++)
    {
        ReadMatrixRow(cin,Sigma,i);
    }

    mu=(double *)malloc(n_size * sizeof(double *));

    cout<<"Input the expected return vector values:"<<endl;

    //WANT A PAUSE HERE FOR FURTHER INPUT THAT IS SEPARATE

    ReadVector(cin,mu);

    for (i=0;i<n_size;i++)
    {
        cout<<mu[i]<<endl;
    }

The functions that read the matrix and the vector are

istream& ReadMatrixRow(istream& in, double **s,int i)
{
    if (in)
    {
        int j=0;
        double x;
        while (in>>x)
        {
            s[i][j]=x;
            ++j;
        }
        in.clear();
        in.ignore(1);
    }
    return in;
}

istream& ReadVector(istream& in, double *s)
{
    if (in)
    {
        int i=0;
        double x;
        while (in>>x)
        {
            s[i]=x;
            ++i;
        }
        in.clear();

    }
    return in;
}

You seem to end the first (and second) loop of input by pressing the end-of-file sequence for your system. That effectively closes the input so your second loop is not executed at all. This should have been very obvious if you just stepped through the code, line by line, in a debugger.

Instead of doing that use a for loop to read the input. That way you will not have to use the end-of-file sequence to terminate the input, you also will (or should) be protected against going out of bounds of your allocated memory (why aren't you using static arrays if you just allocate a fixed number of elements?).

To pause until the user presses a key use the getch(). You need to include conio.h header file to use getch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM