Dec 28, 2017 at 11:59pm UTC
Last edited on Dec 29, 2017 at 12:06am UTC
Dec 29, 2017 at 6:16am UTC
Are you certain a switch is the right tool for your problem?
This looks like an XY problem ( xyproblem.info ). If this is the case, best ask about your problem rather than your attempted solution.
Dec 29, 2017 at 9:56am UTC
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <string>
using namespace std;
int main()
{
const string digits = "0123456789" ;
int i;
cout << "Enter i: " ; cin >> i;
cout << digits.substr( 1, i );
}
I'm inclined to agree with @Ganado and @mbozzi, though:
best ask about your problem rather than your attempted solution.
Last edited on Dec 29, 2017 at 10:02am UTC
Dec 29, 2017 at 11:35am UTC
I'm trying to print three strings in a predetermined order, and the number of strings being printed is
i
so
1 2 3 4 5 6
switch (i)
{
case 1: printf("%s" , "A" );
case 2: printf("%s" , "B" );
case 3: printf("%s" , "C" );
}
So the resulting string is either A, AB, or ABC.
I apologise for the confusion, this has nothing to do with printing numbers, and everything to do with printing strings in a particular order.
Last edited on Dec 29, 2017 at 11:36am UTC
Dec 29, 2017 at 11:58am UTC
Do we actually care what is printed? No. You want something printed "in order".
You can do that with a switch: EDIT: not easily.
1 2 3 4 5 6 7
using std::cout;
switch (i)
{
case 3: cout << "A" ;
case 2: cout << "B" ;
case 1: cout << "C" ;
}
However, a loop is good too:
1 2 3 4 5
std::vector<std::string> words { "A" , "B" , "C" };
for ( int w=0; w < i and w < words.size(); ++w ) {
std::cout << words[w];
}
Last edited on Dec 29, 2017 at 3:32pm UTC
Dec 29, 2017 at 3:09pm UTC
I solved the issue using
std::deque
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <deque>
#include <string>
std::deque<std::string> d;
int i;
switch (i)
{
case 3: d.push_front("C" );
case 2: d.push_front("B" );
case 1: d.push_front("A" );
}
for (auto &it: d) std::cout << it;
Last edited on Dec 29, 2017 at 3:10pm UTC
Jan 4, 2018 at 2:20am UTC
Does a recursive function meet your idea, like this:
string func(int n) {
return n>0 ? func(n-1)+char('A'+n-1) : "";
}
Jan 4, 2018 at 5:37am UTC
OP is working with an XY problem.