我正在使用指針的madlibs程序。當我嘗試構建它時,它的確如此正確,但我認爲它們在動態分配數組時遇到了一些問題,這些數組用於存儲讀取的文本文件中的行。陣列中的數字是文件中的標記值。我還在cout語句中顯示它在錯誤發生前存儲信息。可以幫助嗎?錯誤是圍繞「條目」的堆棧。如何糾正運行時錯誤堆棧周圍的變量是否損壞?
//這裏是我到目前爲止的代碼
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
void header();
//string play_again();
void read_game_file(string **entries, int *num_entries, string **story, int *num_lines);
//string get_user_input(string* entries, int * num_entries);
int main()
{
header();
cout<<endl<<endl;
int num_entries=(NULL);
int *num_lines=(NULL);
string *entries (NULL);
string *story (NULL);
read_game_file(&entries, &num_entries, &story, &*num_lines);
cout<<"doneszo"<<endl;
string get_user_input(string*entries, int * num_entries);
}
void header()
{
cout<<"Hello! Welcome to the game Madlibs."<<endl;
cout<<"The object of the game is to produce something that sounds totally ridiculous."<<endl;
cout<<"So don't think to hard about your answers."<<endl;
cout<<"At the top, you will see a bunch of word descriptions followed by blank spaces."<<endl;
cout<<"Type your word in the blanks. The words should match the descriptions on the left."<<endl;
cout<<"Enter no when you no longer wish to play. Enter yes to continue. Have a great laugh!"<<endl;
}
void read_game_file(string **entries, int *num_entries, string **story, int *num_lines)
{
//Ask user to input file name and opens file
ifstream mad_lib;
string file_name;
cout<<"Please enter the file name with extension: ";
cin>>file_name;
mad_lib.open(file_name);
//Checks to see that file name is valid if not ask for input again
if (!mad_lib)
{
cout<<"File could not be opened. Please try again"<<endl;
cout<<"Please enter the file name with extension: ";
cin>>file_name;
mad_lib.open(file_name);
}
int work;
string line;
mad_lib>>work;
num_entries=&work;
getline(mad_lib,line);
*entries=new string[*num_entries];
cout<<*num_entries<<endl;
string * entry;
for(int i=0; i<*num_entries; i++)
{
entry = new string;
getline(mad_lib,*entry);
entries[i]= entry;
cout<<*(entries[i])<<endl;
}
string work_2;
int work_3;
stringstream ss;
getline(mad_lib,work_2);
ss<<work_2;
ss>>work_3;
cout<<work_2<<endl;
num_lines=&work_3;
*story=new string[*num_lines];
string *entry_2;
for(int j=0; j<=*num_lines; j++)
{
entry_2=new string;
getline(mad_lib,*entry_2);
story[j]= entry_2;
cout<<*(story[j])<<endl;
}
}
你應該避免'**'和'new'的東西。不會'std :: vector'做什麼? –
juanchopanza
'entries [i] = entry;'是你的問題。任何大於0的值都會破壞堆棧。嘗試使用'(*條目)[我]'而不是。 – RonenKr