Answer the question
In order to leave comments, you need to log in
You need to duplicate every third word in the entered C++ string. How can I fix my current code?
wstring s, a, b;
getline(ws(wcin), s);
int k = 0;
int slovo, count = 0;
int i = 0;
while (s[i] == ' ' && s[i] != '\0')
i++;
slovo = 0;
while (s[i] != '\0') {
if (s[i] != ' ' && slovo == 0)
{
slovo = 1;
count++;
if (count%3==0)
{
int pos = i + 1;
while (iswspace(s[pos])) pos--;
while (!iswspace(s[pos])) pos--;
int len = abs(pos - i);
if (s[i + 1] == '\0') len++;
while (--len >= 0)
{
for (int q = pos; s[q] != '\0'; q++)
a += s[q];
b += L"" + a;
s.insert(i - 1 , L"" + a);
i += a.length() + 1;
a = L"";
count = 0;
}
}
}
else if (s[i] == ' ')
slovo = 0;
i++;
}
wcout << L"\nРезультат: ";
wcout << s;
Answer the question
In order to leave comments, you need to log in
Here's what I wrote quickly for your problem:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string str;
std::cout << "Enter string: ";
std::getline(std::cin, str);
std::stringstream s(str);
std::string tmp, res;
int count = 0;
while(s >> tmp) {
res += tmp + ' ';
++count;
if(count%3==0) res += tmp + ' ';
}
res = res.substr(0, res.length()-1);
std::cout<<res;
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question