2014-02-09 46 views
1

我想知道如何使用流读取文件,但也可以在函数内使用它们。 到目前为止,我的代码是;:使用函数读取文件C++

#include <iostream> 
#include <fstream> 
#include <cstdlib> 
#include <string> 
using namespace std; 
void burbuja(int[]); 
void imprimeArreglo (int[],int); 
void leeArchivo(string&); 
int arreglo[10]; 
int i; 

void burbuja (int a[]) 
{ 
int i,j; 
    for(i=0;i<10;i++) 
    { 
     for(j=0;j<i;j++) 
     { 
      if(a[i]>a[j]) 
      { 
       int temp=a[i]; //swap 
       a[i]=a[j]; 
       a[j]=temp; 
      } 

     } 

    } 
} 
void imprimeArreglo(int a[],int tam) 
{ 
    for(int i=0;i<tam;i++) 
    cout << a[i] << " "; 
} 
void leeArchivo(string& nombre) 
{ 
string filename = nombre; 
ifstream myfile(filename); 
string line; 
if (myfile.is_open()) { 
while (getline (myfile,line)) 
    { 
     cout << line << '\n'; 
    } 
    myfile.close(); 
} 
else cout << "Unable to open file"; 


} 
int main() 
{ 
    string nombre = "arr.txt"; 

    leeArchivo(nombre); 
     cin >> i ; 
     return 0; 
} 

我希望能够从main方法调用leeArchivo(“arr.txt”)。 有了这个我得到的错误:

Error: bubble.cpp(37,14):'ifstream' is not a member of 'std' 
Error: bubble.cpp(37,19):Statement missing ; 
Error: bubble.cpp(39,20):Undefined symbol 'file' 
Error: bubble.cpp(39,25):Could not find a match for 'std::getline(undefined,std::basic_string<char,std::string_char_traits<char>,std::allocator<char>>)' 

我在这里想念什么? (我是新的C++) 我试图读取的文件的结构如下: <number>

<number> <number> <number> ...

EG:

=========================================

编辑: 我使用Borland C++ 5.02

编辑2: 更新代码,使用Geany现在的错误是:BUBBLE.cpp:38:25: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'

+3

1)你的主要功能有没有返回类型,2)你'使用命名空间std;'但在某些地方仍然会把'std ::'放入。只要移除using指令并指定'std ::',3)['std :: ifstream'](http://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream)绝对是名字空间的一员'std ::' – Borgleader

+2

那就是说,你使用的是编译器吗? (我很惊讶它没有提到main没有返回类型) – Borgleader

+1

在main()的非标准声明之外,[这应该正确编译](http://ideone.com/KDy4mj)。无论您在发布代码时从代码中剥离了哪些内容,都将其恢复并更新该帖子。在这样做的同时,还要添加您正在构建的编译器和平台。 (我会使用'cstdlib',但不应该导致你遇到的问题;你* *没有显示的代码是负责的)。报告的错误声称他们在第37和第39行。显然缺少某些东西。 – WhozCraig

回答

1

这是特别奇怪的行为与ifstream。试试这个编辑:

void leeArchivo(const string&); 
void leeArchivo(const string& nombre) 
{ 
    ifstream file(nombre.c_str()); 
    string line; 
    while(getline(file,line)) { 
     cout << line << endl; 
    } 
} 

int main() 
{ 
    leeArchivo("arr.txt"); 
    return 0; 
} 

此外,使用:

#include <cstdlib> 

相反的:

#include <stdlib.h> 
+0

尝试使用cstdlib时出现错误。 '错误:bubble.cpp(2,2):无法打开包含文件'CSTDLIB.h' –

+0

@DavidMerinos:您正在尝试'#include '。这不存在。它应该是:'#include '。 – jrd1

+0

不,我的代码是:'#include ' –