为什么我需要在用户为其赋值之前初始化此变量

Why do I need to initialise this variable before the user assigns a value to it?

本文关键字:赋值 初始化 变量 用户 为什么      更新时间:2023-10-16

我希望用户为 int temp1 和 int temp2 分配一个值。但是,编译器说我需要初始化两个变量之一(temp2)。

为什么它只要求我初始化 temp2 而不是 temp1?当我为 temp2 分配一个值时,程序会忽略用户输入的任何值。

我的代码是否草率,如果是这样,有没有办法解决这个问题?

(我已经包含了整个程序,以防它相关,但是我收到的错误是在inputDetails()函数中。

#include <iostream>
using namespace std;
//Prototype
void inputDetails(int* n1, int* n2);
void outputDetails(int num1, int num2, int* pNum, int* n1, int* n2, int** ppNum);
//Functions
int main()
{
int num1;
//num1 pointer
int* n1 = &num1;
int num2;
//num2 pointer
int* n2 = &num2;
//get pNum to point at num1
int* pNum;
pNum = new int;
*pNum = num1;
//pointer to pNum
int** ppNum = &pNum;
//call functions
inputDetails(n1, n2);
outputDetails(num1, num2, pNum, n1, n2, ppNum);
//change pNum to point at num2
delete pNum;
pNum = new int;
*pNum = num2;
//call function again
outputDetails(num1, num2, pNum, n1, n2, ppNum);
delete pNum;
system("PAUSE");
return 0;
}
void inputDetails(int* n1, int* n2)
{
int temp1, temp2;
cout << "Input two numbers" << endl;
cin >> temp1, temp2;
*n1 = temp1;
*n2 = temp2;
}
void outputDetails(int num1, int num2, int* pNum, int* n1, int* n2, int** ppNum)
{
cout << "The value of num1 is: " << num1 << endl;
cout << "The address of num1 is: " << n1 << endl;
cout << "The value of num2 is: " << num2 << endl;
cout << "The address of num2 is: " << n2 << endl;
cout << "The value of pNum is: " << pNum << endl;
cout << "The dereferenced value of pNum is: " << *pNum << endl;
cout << "The address of pNum is: " << ppNum << endl;
}

为什么它只要求我初始化temp2而不是temp1

以下内容不会执行您认为它的作用(它无意中使用了逗号运算符):

cin >> temp1, temp2;

要从cin读取两个值,请使用:

cin >> temp1 >> temp2;