tags:

views:

118

answers:

3

Hi, I have a simple text file, that has following content

word1 word2

I need to read it's first line in my C++ application. Following code works, ...

std::string result;
std::ifstream f( "file.txt" );
f >> result;

... but result variable will be equal to "word1". It should be equal to "word1 word2" (first line of text file) Yes, i know, that i can use readline(f, result) function, but is there a way to do the same, using >> style. This could be much more pretty. Possible, some manipulators, i don't know about, will be useful here ?

+1  A: 

No, there isn't. Use getline(f, result) to read a line.

Roger Pate
A: 

You can create a local that only has newlines as whitespace, but that would be a confusing hack. Here is an example doing just that with commas.

Judge Maygarden
+1  A: 

Yes define a line class and define the operator >> for this class.

#include <string>
#include <fstream>
#include <iostream>


struct Line
{
    std::string line;

    // Add an operator to convert into a string.
    // This allows you to use an object of type line anywhere that a std::string
    // could be used (unless the constructor is marked explicit).
    // This method basically converts the line into a string.
    operator std::string() {return line;}
};

std::istream& operator>>(std::istream& str,Line& line)
{
    return std::getline(str,line.line);
}
std::ostream& operator<<(std::ostream& str,Line const& line)
{
    return str << line.line;
}

void printLine(std::string const& line)
{
    std::cout << "Print Srting: " << line << "\n";
}

int main()
{
    Line    aLine;
    std::ifstream f( "file.txt" );
    f >> aLine;

    std::cout << "Line: " << aLine << "\n";
   printLine(aLine);
}
Martin York