Need some editing on code

So basiclly I need to ask user what book he is reading.

and then when he types it , it must display like this

What Book are you reading? Learning with C++ (User Input)

Output :

Learning
With
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <string>
using namespace std;
auto split(const string& str, const string& delim)
{
vector<std::string> vs;
size_t pos {};
for (size_t fd = 0; (fd = str.find(delim, pos)) != string::npos; pos = fd + delim.size())
vs.emplace_back(str.data() + pos, str.data() + fd);
vs.emplace_back(str.data() + pos, str.data() + str.size());
return vs;
}
int main()
{
const auto vs {split("what,book,is,that,you,are,reading", ",")};
for (const auto& e : vs)
cout << e << '\n';
}
Last edited on
It's easier using std::stringstream:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <sstream>
#include <iostream>

int main() {
	std::string str;

	std::cout << "What book are you reading? ";
	std::getline(std::cin, str);

	std::istringstream iss(str);

	for (std::string w; iss >> w; std::cout << w << '\n');
}



What book are you reading? Learning With C++
Learning
With
C++

Last edited on
Not as eloquent as seeplus's solution, but one for beginners.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
using namespace std;


int main()
{

string s;

cout << "What book are you reading? ";

getline(cin, s);


for(int i = 0; i < s.length(); i++) {
    if(s[i] == ' ') {
        cout << endl;
    }
    else {
     cout << s[i];   
    }
        
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
using namespace std;

int main() {
	string s;

	cout << "What book are you reading? ";
	getline(cin, s);

	for (char c : s)
		cout << (c == ' ' ? '\n' : c);
}

Topic archived. No new replies allowed.