To my best knowledge, std::getline() can route data only to std::string , that is why I need to come up with something else, as my project is not allowed to use std::string class.
Note that std::getline
and std::istream::getline
are two separate functions. The former will work with std::string
while the latter will work with C-style strings (i.e. sequences of characters that are terminated by a null character).
Therefore, if you are not allowed to use std::string
, then you can still use std::istream::getline
, for example like this:
char line[200];
String street;
std::cout << "Street: ";
if ( std::cin.getline( line, sizeof line ) )
{
//the array "line" now contains the input, and can be assigned
//to the custom String class
street = line;
}
else
{
//handle the error
}
This code assumes that your custom class String
has defined the copy assignment operator for C-style strings.
If it is possible that the lines will be larger than a fixed number of characters and you want to support such lines, then you could also call std::istream::getline
in a loop:
char line[200];
String street;
std::cout << "Street: ";
for (;;)
{
std::cin.getline( line, sizeof line );
street += line;
if ( std::cin.bad() )
{
//TODO: handle error and break loop, for example by
//throwing an exception
}
if ( !std::cin.fail() || std::cin.eof() )
break;
std::cin.clear();
}
This code assumes that operator +=
is defined for class String
.
This loop will continue forever until
getline
succeeds (i.e. it is able to extract (but not store) the newline character), or
end-of-file is reached (eofbit
is set), or
an error occurs (badbit
is set).