动态数组输出问题
我正在做一个家庭作业,我必须使用指针将程序中的所有静态数组转换为动态数组。我很确定我正在理解这个概念,我已经进行了更改并且我的程序可以运行。问题出在我的输出结果上。我怀疑我从正在使用的文件中输入的数据不正确。这是我的问题的图片以及相关代码:
此点之后的 9 月 21 日编辑:
输出 &数据文件:
主要
#include "Ch9_Ex7.h"
int main()
{
int numCandidates;
string *allCandidates;
int *votes;
int index, totalVotes;
ifstream infile;
allCandidates = new string[1];
votes = new int[1];
infile.open("./Ch9_Ex7Data.txt");
if (!infile)
{
cerr << "Cannot open input file. Program terminates!" << endl;
return 1;
}
// read number of candidates
readVotes (infile, votes, allCandidates, numCandidates);
//delete [] votes;
//delete [] allCandidates;
输入功能:
#include "Ch9_Ex7.h"
void readVotes (ifstream & infile, int *&votes,
string *&allCandidates, int & numCandidates)
{
// read number of candidates
infile >> numCandidates;
infile.ignore(); // carriage return
//delete [] votes;
//delete [] allCandidates;
allCandidates = new string[numCandidates];
votes = new int[numCandidates];
for (int index = 0; index < numCandidates; index++)
{
infile >> votes[index];
infile.ignore(); // space
getline(infile, allCandidates[index]);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用以下代码创建一个由一个
char
和一个int
组成的数组:我相信您的意思是:
它创建大小为
numCandidates
的动态数组。另外,当您输入候选人的姓名时,您可能想使用
std::string
,如下所示:(感谢 Ben Voigt 指出这一点)既然您输入了他们的全名,您将需要以不同的方式输入。也许使用 getline() :
响应您的编辑:
您必须将指针作为引用传递,如下所示:
并在 main() 中释放它们
You are creating an array of one
char
and oneint
with this code:I believe you meant:
which creates dynamic arrays of size
numCandidates
.Also, as you are inputting names of candidates you probably wanted to use
std::string
like so:(Thanks to Ben Voigt for pointing that out) And since you're inputting their full name you'll need to input it differently. Perhaps use
getline()
:In response to your edit:
You will have to pass your pointers as references like so:
and free them in
main()
首先,这绝对是糟糕的设计,所以请不要在本练习的范围之外这样做。
现在,回答问题。如果你想在某处创建一个动态对象(或数组)并将指针传递回它,你应该通过引用获取指针。您还必须将名称读入字符串,而不是单个字符。
调用者必须记住清理:(
在现实情况下,我会让函数返回一个
std::vector>
.)First off, this is absolutely terrible design, so please don't do this outside the scope of this exercise.
Now, on to the question. If you want to create a dynamic object (or array) somewhere and pass the pointer to it back, you should take the pointer by reference. You also have to read the names into a string, not into a single character.
The caller has to remember to clean up:
(In a real-world situation, I would have the function return a
std::vector<std::pair<int, std::string>>
.)