Search code examples
c++istream

Read from istream with possible '\n' symbols


I need to read from istream some strings, of which there are two types:

  1. " strings with leading and trailing spaces " which should look like "strings with leading and trailing spaces" (only leading and trailing spaces are trimmed, what's within them is kept)
  2. " John Doe \n Mary Smith". Here I need to a) read only until the '\n' and b) delete the leading spaces while retaining the trailing spaces so the string I get is "John Doe " (mind that the trailing spaces are still there).

I got confused about how I can read the line and get to know if there are more that one '\n' in it.


Solution

  • You can read the string with std::getline, and if it is multiline, then leave trailing spaces, if not, remove them too:

    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main()
    {
        //std::istringstream iss("   strings with leading and    trailing spaces   ");
        std::istringstream iss("  John Doe    \n  Mary Smith");
    
        std::string lines[2];
        size_t i = 0;
        bool keep_trailing_spaces = false;
        while (std::getline(iss, lines[i++], '\n'))
        {
            if (i > 1)
            {
                keep_trailing_spaces = true;
                break;
            }
        }
    
        if (i > 1)
        {
            size_t start = lines[0].find_first_not_of(' ');
            size_t count = keep_trailing_spaces ? std::string::npos : lines[0].find_last_not_of(' ') - start + 1;
    
            std::cout << ">" << lines[0].substr(start, count) << "<" << std::endl;
        }
    
        return 0;
    }
    

    https://ideone.com/tLBiSb

    1st result: >strings with leading and trailing spaces<

    2nd result: >John Doe <