getline function

I'm having issues using the getline function to read words from an input file into a string. I will then use member functions on these words later in the program. The words in the input file are listed vertically. I have no other functions written pertaining to getline except for what's in my code below...do I need to reference it anywhere else? I'm also wondering if the [count++] is the culprit thought I still get an error when I delete it...I put that to keep reading in words from the inputfile until it reaches the end.

I'm getting the error message below, and so far this is my only error message in the program.
"No instance of overloaded function getline matches the argument list"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string WORD;//word from the input file that is randomly chosen

string readFile()
{	
	int count = 0;
	ifstream Words("inputfile.txt");
	if (Words.is_open())
		cin.ignore(1, '\n');//gonna comment this out
	{
		while ((!Words.eof()))//while end of file is not reached, keep reading the words
		{
			getline(Words, WORD[count++]);
			//Read the words from the file into the string WORD
			//Get the next word and then increment count 
		}
	}
}
The problem lies in the second parameter of your function call.
Here's your declared variable an how you're passing it into the function:
1
2
string WORD;
getline(Words, WORD[i]);

The problem is you didn't declare "WORD" as a string array but rather a single string object. Which means using the subscript operator [] accesses the character of the string at position i.

In short, you're passing the wrong type of variable into your getline function. It calls for a string type for its second parameter, but you're actually passing a char.

Create a string array instead:
1
2
string WORD[#];
getline(Words, WORD[i]);
Last edited on
Thank you, I tried to establish a string array like this, and I'm getting the errors below, especially the "string" is ambiguous error:

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>

using namespace std;

typedef char string[20];//string of 20 words
string WORD[7];//each word is an array of up to 7 chars

//function declarations begin....

Errors:

cannot convert argument 1 from 'std::string [70]' to 'std::string'

IntelliSense: no instance of overloaded function "getline" matches the argument list
argument types are: (std::ifstream, <error-type>)

IntelliSense: "string" is ambiguous
Topic archived. No new replies allowed.