Markus Fürst Markus Fürst - 20 days ago 9
C++ Question

Insert a new line after each dot, C++

I have this code and I want to insert a new line after each dot with a insert statement. I get the error message no matching member function for call to 'insert'. What am I doing wrong?

#include<iostream>
#include<string>


using namespace std;

int main ()
{
string const inText1 = "I'm reading. ";
string const inText2 = "I like to read. ";
string const inText3 = "I'm gonna read that book. ";
string const inText4 = "She's reading. ";
string const inText5 = "He's reading. ";
string const inText6 = "READ. ";
string const inText7 = "Reading. ";

string inText8=inText1+inText2+inText3+inText4+inText5+inText6+inText7;

string::size_type dotpos = inText10.find(".");
if(dotpos != string::npos)
inText10.insert(dotpos, endl);


cout << inText10 << endl;


return 0;
}

Answer

The code below works for me:

Edit: I change your if statement with a while() because you need to do this for each '.'

#include<iostream>
#include<string>

using namespace std;

int main ()
{ 
    string const inText1 = "I'm reading. ";
    string const inText2 = "I like to read. ";
    string const inText3 = "I'm gonna read that book. ";
    string const inText4 = "She's reading. ";
    string const inText5 = "He's reading. ";
    string const inText6 = "READ. ";
    string const inText7 = "Reading. ";

    string inText8=inText1+inText2+inText3+inText4+inText5+inText6+inText7;


    string::size_type dotpos = 0;
    dotpos = inText8.find(".", dotpos + 1);
    while(dotpos != string::npos){
        inText8.insert(dotpos + 1, 1, '\n');
        dotpos = inText8.find(".", dotpos + 1);
    }

    cout << inText8 << endl;

    return 0;
}