Default Arguments
Completed
Write string repeat(const string &s, int times = 2, const string &sep = "-"). For each input line with 1, 2 or 3 parts, call it with that many arguments and print the result.
Input
n, then n lines.
Output
n lines.
Example
Input
3 ab xy 4 hi 3 +
Output
ab-ab xy-xy-xy-xy hi+hi+hi
Editor
C++
Hints
Default values are used for arguments you leave out.
After cin >> n, call getline once to finish that line.
Solution explanation
Default arguments must come last in the parameter list.
Show solution
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string repeat(const string &s, int times = 2, const string &sep = "-") {
string out;
for (int i = 0; i < times; i++) {
if (i > 0) out += sep;
out += s;
}
return out;
}
int main() {
int n;
cin >> n;
string line;
getline(cin, line);
for (int i = 0; i < n; i++) {
getline(cin, line);
istringstream in(line);
string word, sep;
int times;
in >> word;
if (!(in >> times)) {
cout << repeat(word) << "\n";
} else if (!(in >> sep)) {
cout << repeat(word, times) << "\n";
} else {
cout << repeat(word, times, sep) << "\n";
}
}
return 0;
}