Home > Mobile >  Remove ' ' after the last output [closed]
Remove ' ' after the last output [closed]

Time:10-06

I have a C code that calculates change.

It takes input, and returns output by how change will be received.

I need to remove the sign after last change output.

Is there a way to do this?

My code:

if (n500 > 0) {
        cout << n500 << " x 500   ";
    }
    if (n200 > 0) {
        cout << n200 << " x 200   ";
    }
    if (n100 > 0) {
        cout << n100 << " x 100   ";
    }
    if (n50 > 0) {
        cout << n50 << " x 50   ";
    }
    if (n20 > 0) {
        cout << n20 << " x 20   ";
    }
    if (n10 > 0) {
        cout << n10 << " x 10   ";
    }
    if (n5 > 0) {
        cout << n5 << " x 5   ";
    }
    if (n2 > 0) {
        cout << n2 << " x 2   ";
    }
    if (n1 > 0) {
        cout << n1 << " x 1   ";
    }
    return 0;
}

CodePudding user response:

I would do the other way: put the separator " " when previous display has already be done:

const char* sep = "";
if (n500 > 0) {
    std::cout << sep << n500 << " x 500";
    sep = "   ";
}
if (n200 > 0) {
    std::cout << sep << n200 << " x 200";
    sep = "   ";
}
if (n100 > 0) {
    std::cout << sep << n100 << " x 100   ";
    sep = "   ";
}
if (n50 > 0) {
    std::cout << sep << n50 << " x 50   ";
    sep = "   ";
}
if (n20 > 0) {
    std::cout << sep << n20 << " x 20   ";
    sep = "   ";
}
if (n10 > 0) {
    std::cout << sep << n10 << " x 10   ";
    sep = "   ";
}
if (n5 > 0) {
    std::cout << sep << n5 << " x 5   ";
    sep = "   ";
}
if (n2 > 0) {
    std::cout << sep << n2 << " x 2   ";
    sep = "   ";
}
if (n1 > 0) {
    std::cout << sep << n1 << " x 1   ";
    sep = "   ";
}

BTW, you might probably use loop instead:

const int ns[9] = {
    n500, n200, n100,
    n50, n20, n10,
    n5, n2, n1
};
const char* texts[9] = {
    " x 500", " x 200", " x 100",
    " x 50", " x 20", " x 10",
    " x 5", " x 2", " x 1"
};

const char* sep = "";
for (int i = 0; i != 9;   i) {
    if (ns[i] > 0) {
       std::cout << sep << ns[i] << texts[i];
       sep = "   ";
    }
}

CodePudding user response:

Set a string with all your update, remove the last char then output it with cout.

Look at stringstream

  • Related