midnightBlue
midnightBlue

Reputation: 1825

C++: #included <fstream> but cannot use getline?

My Code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
.
.
.

void function() {
    ofstream inputFile;
    .
    .
    .
    inputFile.getline (inputFile, inputField1, ",");
}

For some reason I can't figure out, compiling this using g++ returns

error: ‘struct std::ofstream’ has no member named ‘getline’

Also, as a side note, it also generates errors

error: invalid conversion from ‘void*’ to ‘char**’
error: cannot convert ‘std::string’ to ‘size_t*’ for argument ‘2’ to ‘ssize_t getline(char**, size_t*, FILE*)’

But I think I got the parameters the wrong way round or something.

Can anyone help shed any light?

Upvotes: 2

Views: 9344

Answers (4)

Adrian G
Adrian G

Reputation: 785

There are two getline functions which take delimiters in c++.

One is in ifstream:

istream& getline (char* s, streamsize n, char delim);

The other is in string:

istream& getline (istream& is, string& str, char delim);

It seems from your example that you are anticipating the usage of the one from string.

#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;

int main() {
  ifstream inputFile;
  string inputField1;

  inputFile.open("hi.txt");

  getline(inputFile, inputField1, ',');

  cout << "String is " << inputField1 << endl;

  int field1;
  stringstream ss;
  ss << inputField1;
  ss >> field1;

  cout << "Integer is " << field1 << endl;

  inputFile.close();

}

Upvotes: 3

Ryan Witmer
Ryan Witmer

Reputation: 331

An ofstream is an output file stream. You need an ifstream.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224944

An ofstream is an output stream, so it doesn't have any input methods. You probably want ifstream:

void function() {
    ifstream inputFile("somefilename");
    char buf[SOME_SIZE];
    inputFile.getline (buf, sizeof buf, ',');
}

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227418

An ofstream is an output stream, hence a getlinemethod doesn't make sense. Maybe you need ifstream.

Upvotes: 1

Related Questions