我希望用户为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;
}
答案 0 :(得分:4)
为什么只要求我初始化
temp2
而不是temp1
?
以下内容并不符合您的想法(它无意中使用了comma operator):
cin >> temp1, temp2;
要从cin
读取两个值,请使用:
cin >> temp1 >> temp2;