由于某种原因,我无法弄清楚为什么打开时的数据不会被放入数组并且程序崩溃。我一直在寻找无济于事的答案。我觉得在完成这个程序之前,我会在这里再发几次!
#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;
}
答案 0 :(得分:2)
我看到的一个快速问题是:
infile >> bookTitle [14] ;
infile >> bookAuthor [14];
不正确,您需要的是:
infile >> bookTitle[counter];
infile >> bookAuthor [counter];
另外,
counter
和main()
中声明的loadData()
变量是两个不同的变量。在main()
中声明的那个根本就没有被定罪。
答案 1 :(得分:1)
此代码存在许多问题。
这些行只写入数组的第14个元素
infile >> bookTitle [14] ; //takes input and puts into parallel arrays
infile >> bookAuthor [14];
为了填充整个数组,您需要使用counter
变量作为索引:
infile >> bookTitle [counter] ; //takes input and puts into parallel arrays
infile >> bookAuthor [counter];
BTW :如果数组的大小为14,则最大索引为13.因此您无法访问索引为14的元素。这可能会导致崩溃。
counter
main()
未初始化showall()
函数接受一个参数但不使用它,这可能是索引。showall()
在main()
中调用可能需要处于循环中,以显示所有元素。