1

I'm trying to read the data from a file using pointers but it gives error at the getline part that goes by "no instance of overloaded function". Couldn't figure out how to go about this..

Code is below:

#include<iostream>
#include<fstream>
using namespace std;
void read(const char * const, char const *);
int main()
{
    char filename[20] = { "sentence.txt" }, data[50] = { '\0' };
    read(filename, data);
    return 0;
}

void read(const char * const ptr, char const * ptr2)
{
    ifstream file;
    file.open(ptr);
    if (!file.is_open())
    {
        cout << "File not found " << endl;
        exit(0);
    }
    else
    {
        while (!file.eof())
        {
            file.getline(ptr2, 49, ' ');
            cout << ptr2 << endl;
        }
        file.close();
    }
}
scypx
  • 67
  • 7
  • shouldn't ptr2 be const char * instead of char const * ? – miep Jun 09 '20 at 12:54
  • @miep they're utterly identical – Alexey S. Larionov Jun 09 '20 at 12:56
  • @AlexLarionov , yeah, i just realized. My bad there. – miep Jun 09 '20 at 12:57
  • @miep well here, the contents in the array can change. In const char *, that wouldn't be possible – scypx Jun 09 '20 at 13:03
  • 1
    @scypx `const char * ptr` and `char const * ptr` are the same thing. These are both pointers to constant char, i.e. you can't change the content – Alexey S. Larionov Jun 09 '20 at 13:10
  • @Alex Larionov I don't believe that is the case. https://stackoverflow.com/questions/890535/what-is-the-difference-between-char-const-and-const-char#:~:text=19%20Answers&text=The%20difference%20is%20that%20const,(similar%20to%20a%20reference). – scypx Jun 09 '20 at 13:16
  • [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – molbdnilo Jun 09 '20 at 13:28

2 Answers2

2

Function read is already defined in the C++ libraries:

https://en.cppreference.com/mwiki/index.php?title=Special%3ASearch&search=read

You should use a different name for your function.

Also as written in the comments, const char * and char const * are the same. They are pointers to constant char, which doesn't let you modify the contents of the char array. What you probably wanted is constant pointer to char:

char * const
MichalH
  • 1,062
  • 9
  • 20
0

Ok it was just a simple error that I can't believe I didn't see. The asterisk should be before const so correct indentation would be char * const ptr2 and not char const * ptr2

Call me dumb duh.

scypx
  • 67
  • 7