Read in an input value for variable numInput. Then, read numInput integers from input and output each on the same line with the character ": " between each value.
Ex: If the input is 5 10 -15 -95 -25 25, the output is: 10: -15: -95: -25: 25
Note: ": " should not be at the beginning or end of the output.
Currently, the code prints ": "
at the end of the output. How to not print ": " at the end so as to get the expected output?
#include <iostream>
using namespace std;
int main() {
int numInput;
cin >> numInput;
while(cin >> numInput) {
cout << numInput << ": ";
}
cout << endl;
return 0;
}
CodePudding user response:
Very similar to the solution proposed by @RemyLebeau in comments.
#include <iostream>
#include <string>
int main() {
int numInput;
std::string beginning = "";
std::cin >> numInput;
while (std::cin >> numInput) {
std::cout << beginning << numInput;
beginning = ": ";
}
std::cout << std::endl;
return 0;
}
""
will be printed before the first input int
. Subsequently beginning
is changed to ": "
and that will be printed before each input. The end result is that :
will appear after every input except the last one.
CodePudding user response:
You are printing ;
after each input number. You should instead output the 1st number by itself, and then output ;
before each subsequent number, eg:
#include <iostream>
using namespace std;
int main() {
int numInput, input;
if (cin >> numInput && numInput > 0) {
if (cin >> input) {
cout << input;
while (--numInput > 0 && cin >> input) {
cout << ": " << input;
}
cout << endl;
}
}
return 0;
}