-2

I am trying to read a file line by line and then put in variables each word of the line

#include <iostream>
#include <string>

#include <fstream>
#include "record.h"
using namespace std;

void handleline(string& line1, int a)
{
    //cout<<line1[]<<"\n";
}

int main()
{
    string line1[30];
    ifstream myfile("30+.in");
    int a = 0;
    if (!myfile) {
        cout << "Error opening output file" << endl;

        return -1;
    }
    while (!myfile.eof()) {
        getline(myfile, line1[a], '\n');

        handleline(line1, a);
    }
}

the problem is that i cant pass the line as argument in to the function.

any help will be appreciated !

  • 1
    One reason why the code does not work is that your handleline function takes as the first argument a string&, but you called it with a string*. Type mismatch. – Donghui Zhang Oct 20 '16 at 21:39

2 Answers2

1

See if this helps:

void handleline(string & line)
{
    //you have just the one line to work on in this implementation
}

...

while (!myfile.eof()) {
    getline(myfile, line1[a], '\n');

    handleline(line1[a]);

    a++; // you forgot to increment a in your code
}
space_voyager
  • 1,984
  • 3
  • 20
  • 31
0
string line1[30];

defines an array of string.

handleline(line1, a);

passes that array of string into handleline. line1 will decay (What is array decaying?) into a pointer to string, a string *. Unfortunately

void handleline(string& line1, int a)

expects a reference to a string. A single string, not an array of string or a pointer to string.

Since handleline only consumes a single string at a time

void handleline(string& line)
{
    //cout<<line<<"\n";
}

seems more reasonable.

It would be called with

int main()
{
    std::vector<string> line1; // replaced array with resizable array to prevent overflow
    ifstream myfile("30+.in");
    int a = 0;
    if (!myfile) {
        cout << "Error opening output file" << endl;

        return -1;
    }
    string temp; // declares a temporary holder
    while (getline(myfile, temp, '\n')) // reads file into holder. Note this replaces 
                                         // !myfile.eof(), which is a classic bug. 
                                         // More on that later.
    {
        handleline(temp); // consume the one string
        line1.push_back(temp); // store in resizable array if needed.
    }
}

Why is iostream::eof inside a loop condition considered wrong?

Community
  • 1
  • 1
user4581301
  • 33,082
  • 7
  • 33
  • 54