You want the string class from the C++ standard library. It, like any other type from the standard library, exists in the 'std' namespace, so you access it by prefixing it with the namespace and the :: operator, like std::string. You have to #include <string> to get the class definition.
Likewise, this header file defines a "getline" operation that reads a line from an input stream into the string object. You can use this with the "cin" input stream to read from the console, or a file input stream you've opened to read from your file. This function, like other standard functions, is also in namespace std.
// Read a line from the console and echo it
std::string line;
std::getline(std::cin, line);
std::cout << line;
// Read a line from a file and echo it
std::string line;
std::ifstream infile("myfile.txt");
std::getline(infile, line);
std::cout << line;
Naturally you will probably want to check the stream after the getline call because, like any other stream operation, getline can fail (if, for example, there was nothing in the file). A stream can be tested as a boolean value for convenience, such as in an "if" statement. If it is "true" then the stream is still good. If it is "false" then the stream has failed somehow.
// Read a line
std::string line;
if (! std::getline(std::cin, line))
{
std::cerr << "Unable to read a line.\n";
}
else
{
std::cout << "Read a line: " << line << "\n";
}
Regards,
Jake.
Regards,
Jake.
|