문제

I'd like to know how to read a file using streams but also using them inside a function. So far my code is;:

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

I'd like to be able to call leeArchivo("arr.txt") from the main method. With this I get the errors:

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>>)'

What am I missing here? (I'm new to C++) The file I'm trying to read has the following structure: <number>

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

E.G.:

5

19 28 33 0 1

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

EDIT: I'm using Borland C++ 5.02

EDIT 2: Updated code, using Geany Now error is: BUBBLE.cpp:38:25: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'

도움이 되었습니까?

해결책

That's particularly odd behavior with ifstream. Try this edit:

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

Also, use:

#include <cstdlib>

Instead of:

#include <stdlib.h>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top