C++ 的一个Debug 作业

来源:百度知道 编辑:UC知道 时间:2024/06/08 05:30:53
这是我课上的一个Debug作业,偶不知道为什么总是出问题………………

Description
This assignment tests your knowledge of C++ memory management, pointers, and parameter passing. The program contained in wordlist.cpp reads a list of words from a text file, and then displays the words to the console. The program, however, contains run-time errors. These errors all relate to the use of pointers, the passing of parameters, and dynamic memory management.

Your task is to correct these errors. The use of a debugger is very strongly suggested. This will save you time and give you practice using a debugger.

大概就是说,要从一个“words.txt”中读数据并输出。
用一个数组来读,如果内存空间不够要扩大它的size
就是这样了。
还有就是,应该是在39,47,48行有问题(可能还有),main函数也好像有问题。

这是需要修改的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

const int INITIAL_LIST_CAPACITY = 10;

void build_wordlist (string* w

程序问题不少。。。。
首先函数定义错误,改成:
void build_wordlist (string** word_list, int& capacity, string filename)
或者
int build_wordlist (string** word_list, string filename)
否则1)生成的数组大小capacity无法传出2)word_list无法在函数内重定向以后无法传出

然后里面判断读文件是否结束的条件也错。。。一言难尽,全都帮你改好了
运行正确,用windiff对照一下看看哪里改了

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

const int INITIAL_LIST_CAPACITY = 10;

void build_wordlist (string** word_list, int& capacity, string filename) {

ifstream words;
string word;
int size = 0;

// Allocate the space for the word list
*word_list = new string[INITIAL_LIST_CAPACITY];
capacity = INITIAL_LIST_CAPACITY;

// Open the file
words.open (filename.c_str());

if (!words) {
cerr << "Could not o