我正在使用指针开发一个 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;
}
}