Infile不完整类型错误

时间:2012-03-22 05:24:27

标签: c++ arrays function file-io

我正在构建一个以这种格式输入文件的程序:

title author

title author

etc

and outputs to screen 

title (author)

title (author)

etc

我目前遇到的问题是错误:

  

“ifstream infile类型不完整且无法定义”

以下是该计划:

#include <iostream>              
#include <string>
#include <ifstream>
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);
}


int loadData (string pathname) // Loads data from infile into arrays
{
    ifstream infile; 
    int counter = 0;
    infile.open(pathname); //Opens file from user input in main
    if( infile.fail() )
     {
         cout << "File failed to open";
         return 0;
     }   

     while (!infile.eof())
     {
           infile >> bookTitle [14];  //takes input and puts into parallel arrays
           infile >> bookAuthor [14];
           counter++;
     }

     infile.close;
}

void showall (int counter)        // shows input in title(author) format
{
     cout<<bookTitle<<"("<<bookAuthor<<")";
}

2 个答案:

答案 0 :(得分:15)

文件流在标题<fstream>中定义,您不包括它。

你应该添加:

#include <fstream>

答案 1 :(得分:0)

以下是修复上一个错误的代码现在我输入文本文件名后出现程序崩溃的问题。

#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);
}


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 [14];  //takes input and puts into parallel arrays
           infile >> bookAuthor [14];
           counter++;
     }

     infile.close();
}

void showall (int counter)        // shows input in title(author) format
{

     cout<<bookTitle<<"("<<bookAuthor<<")";







}