出于某种原因,我无法弄清楚为什么打开时数据没有放入数组中,并且程序崩溃了。我四处寻找答案无济于事。我觉得在我完成这个程序之前我会在这里多发几次!
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string bookTitle [14];
string bookAuthor [14];
int loadData (string pathname);
void showall (int counter);
int main ()
{
int counter;
string pathname;
cout<<"Input the name of the file to be accessed: ";
cin>>pathname;
loadData (pathname);
showall (counter);
cout<<"Press <Enter> to Exit";
cin.ignore();
cin.get();
return 0;
}
int loadData (string pathname) // Loads data from infile into arrays
{
fstream infile;
int counter = 0;
infile.open(pathname.c_str()); //Opens file from user input in main
if( infile.fail() )
{
cout << "File failed to open";
return 0;
}
while (!infile.eof())
{
cout<<"File Opened"; // I get the "File Opened" text and then a crash
infile >> bookTitle [14] ; //takes input and puts into parallel arrays
infile >> bookAuthor [14];
cout<<"Data Put in Arrays";
counter++;
}
infile.close();
}
void showall (int counter) // shows input in title(author) format
{
cout<<bookTitle<<"("<<bookAuthor<<")";
}
编辑:任务是获取名称格式为标题的文件 作者 标题 作者 然后它必须以标题(作者)格式将数组输出到屏幕。
在此之后我必须使它成为一个循环程序,以便可以选择其中一个数组进行搜索并以标题(作者)格式返回条目。
代码现在是这样的;
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string bookTitle [50];
string bookAuthor [50];
int loadData (string pathname);
int showall (int counter);
int main ()
{
string pathname;
int counter=0;
cout<<"Input the name of the file to be accessed: ";
cin>>pathname;
loadData (pathname);
showall (counter);
cout<<"Press <Enter> to Exit";
cin.ignore();
cin.get();
return 0;
}
int loadData (string pathname) // Loads data from infile into arrays
{
fstream infile;
int counter = 0;
infile.open(pathname.c_str()); //Opens file from user input in main
if( infile.fail() )
{
cout << "File failed to open";
return 0;
}
while (!infile.eof())
{
infile >> bookTitle [counter] ; //takes input and puts into parallel arrays
infile >> bookAuthor [counter];
counter++;
}
infile.close();
}
int showall (int counter) // shows input in title(author) format
{
cout<<bookTitle<<"("<<bookAuthor<<")";
return 0;
}
最佳答案
我看到的一个快速问题是:
infile >> bookTitle [14] ;
infile >> bookAuthor [14];
不正确,你需要的是:
infile >> bookTitle[counter];
infile >> bookAuthor [counter];
此外,
在main()
和loadData()
中声明的counter
变量是两个不同的变量。在 main()
中声明的那个根本就不会被初始化。
关于c++ - 如何修复导致程序崩溃的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9833534/