【问题标题】:C++ Using Pointers within a Structure (Struct)C++ 在结构 (Struct) 中使用指针
【发布时间】:2013-03-07 03:30:52
【问题描述】:

我正在尝试创建一个程序,询问用户他们有多少婴儿,收集有关每个婴儿的输入,然后将其显示在控制台上。我已经完成了 90% 的路,但我被卡住了。

控制台上的输入/输出应该是这样的;

请输入婴儿数量:2

请输入宝宝#1的身高:21.5

请输入宝宝 #2 的身高:19.75

1 号宝宝的信息: 高度:21.5 英寸

宝宝 #2 的信息: 高度:19.75 英寸

我的代码输出一直显示 19.75 作为两个婴儿的身高。我意识到我可能需要使用指针为 aBaby.height 动态分配不同的值,但我之前没有在结构中使用过指针。任何帮助将不胜感激。

#include <iostream>
using namespace std;

struct Baby {
double length;
};
int main ()
{    
int iNumBaby = 0;

cout<<"Please enter the number of babies: ";
cin>>iNumBaby;
cout<<endl;
Baby aBaby;

Baby* pBaby = new Baby[iNumBaby];

for(int i = 0; i < iNumBaby; i++)
{
cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
cin >> aBaby.length;
cout << "\n";
}  
for(int i = 0; i < iNumBaby; i++)
{
cout << "\Baby #"<<i + 1<<"'s info:\n";
cout << "Height: " <<aBaby.length<<" inches"<<endl;
cout << "\n";
}
system("PAUSE");  
delete[] pBaby;
return 0;
}

【问题讨论】:

  • 不需要大粗体。

标签: struct dynamically-generated member-function-pointers


【解决方案1】:

这与指针无关,您只是代码中有错误。请参阅以下块:

for(int i = 0; i < iNumBaby; i++)
{
    cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
    cin >> aBaby.length;
    cout << "\n";
}

这里的主要问题是您每次都将条目存储到aBaby.length。事实上,您从未在代码中的任何地方使用过pBaby。我想这就是你想要的:

for(int i = 0; i < iNumBaby; i++)
{
    cout << "Please enter baby #" << i + 1 << "'s height <inches>: ";
    cin  >> pBaby[i].length;
    cout << "\n";
}

for(int i = 0; i < iNumBaby; i++)
{
    cout << "Baby #" << i + 1 <<"'s info:\n";
    cout << "Height: " << pBaby[i].length << " inches" << endl;
    cout << "\n";
}

【讨论】:

  • 谢谢你们。这确实是一个语法错误,我对此很陌生。不得不更改为 cin >> pBaby[i].length;和 cout
【解决方案2】:
for(int i = 0; i < iNumBaby; i++)
{
cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
cin >> aBaby.length;
cout << "\n";
}  

问题在于您对 aBaby.length 的分配。您将每个婴儿的长度分配给同一个对象。尝试访问您创建的婴儿数组并更改它们的长度。 示例:

cin >> pBaby[i].length

【讨论】:

    猜你喜欢
    • 2022-06-18
    • 2010-09-25
    • 1970-01-01
    • 2019-03-27
    • 2021-07-14
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多