Reputation: 141
I want to be able to read a full line into a character array using a function.
example input text is:
Schmidt, Helga
Alvarez, Ruben
Zowkowski, Aaron
Huang, Sun Lee
Einstein, Beverly
However, im not sure how to read a full line of characters into the array. I know the delimiter for >> is whitespace, but I'm not sure if I change that delimiter to '\n' if it'd work?
void buildList(char (*array)[25], ifstream& inputFile){
string line;
for (int i = 0; i < 5; i++)
getline(inputFile, line);
array[i] = line.c_str();
}
Currently this only reads either a last name or first name into my input instead of the whole line. I'm not sure how I can go about changing this. Thanks.
Upvotes: 2
Views: 6930
Reputation: 955
Use this-
void buildList(char (*array)[25], ifstream& inputFile){
for (int i = 0; i < 5; i++)
std::inputFile.getline(array[i],50);
}
The second parameter of getline
is the maximum number of characters to write to the character array.
Upvotes: 1
Reputation: 153909
First, you definitely want to use std::string
here. Once you
do that, you can use std::getline
:
std::vector<std::string>
buildList( istream& input )
{
std::vector<std::string> results;
std::string line
while ( std::getline( input, line ) ) {
results.push_back( line );
}
}
This will make for much simpler and more robust code.
If you have to use such a broken interface, there is a member
function getline
:
for ( int i = 0; i != 5; ++ i ) {
input.getline( array[i], maxLength );
}
Also: a function should never take an std::ifstream&
as
argument (unless it is going to open or close the file). An
std::istream&
should be used.
Upvotes: 5