Need some editing on code
Jun 29, 2022 at 8:07am UTC
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 Jun 29, 2022 at 8:08am UTC
Jun 29, 2022 at 8:33am UTC
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 Jun 29, 2022 at 8:35am UTC
Jun 30, 2022 at 5:53pm UTC
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];
}
}
}
Jul 1, 2022 at 8:57am UTC
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.