[英]Pausing for input C++
我正在嘗試編寫一些代碼,以允許輸入矩陣,然后計算矩陣的逆值,然后再輸入向量。 但是,一旦輸入了矩陣值,我就無法使代碼暫停並等待向量輸入,默認情況下,它只是執行剩余的主要部分,用零填充向量。 是否可以重置輸入或其他方式,以便控制台在我要填充矢量時等待輸入?
#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;
}
讀取矩陣和向量的函數是
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;
}
您似乎通過按系統的文件結束序列來結束第一個(和第二個)輸入循環。 這有效地關閉了輸入,因此根本不會執行第二個循環。 如果您只是在調試器中逐行瀏覽代碼,這應該非常明顯。
而不是使用for
循環讀取輸入。 這樣,您將不必使用文件結尾序列來終止輸入,還可以(或應該)防止超出分配的內存范圍(為什么不使用靜態數組,如果您只是分配固定數量的元素?)。
要暫停直到用戶按下某個鍵,請使用getch()。 您需要包括conio.h頭文件才能使用getch
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.