Carlos
Carlos

Reputation: 13

C++ getline errors using char arrays

I keep getting an error saying " error: no matching function for call to 'getline(std::ifstream&, char [100])'| " on getline(Input, sentence). I might be missing something, Im not sure. What I'm trying to do is read an entire line from the input and insert it into char sentence[100] using getline. I have to use getline per the requirements for the assignment. Thank you in advance.

char uniqueWords[100][16] = {""};
int multipleWords = 0;
int theWords[100];
int totalWords = 0;
char sentence[100];
char delimit[] = " /.";


ifstream Input;
Input.open("input.txt");
if (!Input.is_open())
{
    cout << "Error Opening File";
    exit(EXIT_FAILURE);
}

ofstream Output;
Output.open("output.txt", std::ios_base::app);
if (!Output.is_open())
{
    cout << "Error Opening File";
    exit(EXIT_FAILURE);
}


char *p;

while(!Input.eof())
{
    getline(Input, sentence);
    p = strtok(sentence, delimit);
    while(p)
    {
        Output << p ;
        words(p, uniqueWords, theWords, multipleWords);   // a function for the assignment
        totalWords++;
        p = strtok(nullptr,delimit);
    }
    create << "." << endl;
}

Upvotes: 1

Views: 891

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84642

The problem is you are attempting to use std::getline instead of std::basic_istream::getline. (e.g. you are using the wrong getline()) The getline() you are attempting to use expects a std::string for destination storage, not a plain old character array. The second form above happily takes a character array and its size for destination storage. You can use:

    while (Input.getline(sentence, sizeof sentence))
    {
        p = strtok (sentence, delimit);
        while (p)
        {
            Output << p ;
            words (p, uniqueWords, theWords, multipleWords);   // a function for the assignment
            totalWords++;
            p = strtok(nullptr,delimit);
        }
        std::cout << ".\n";
    }

Other thoughts, have a look at Why !.eof() inside a loop condition is always wrong.. Note, control your read-loop with the stream-state which is available as a return from your input function. Also see Why is “using namespace std;” considered bad practice?.

When you output an error message, use std::cerr to write to stderr instead of stdout. For example:

    std::ifstream Input ("input.txt");
    if (!Input.is_open())
    {
        std::cerr << "Error Opening File.\n";
        exit (EXIT_FAILURE);
    }

Other than that, you should really use std::string for your string storage and std::vector<std::string> for storage of a collection of strings. You can copy each string to a character array for parsing with strtok(). Look things over and let me know if you have further questions.

Upvotes: 2

Related Questions