简体   繁体   中英

How do i get rid of the last comma? c++ is reading from a file and reading the numbers backwards

C++ is reading from a file and printing out the numbers backwards. i got rid of the comma when it prints out forward. But I cannot figure out how to do the same for back wards.

so far this is what I have:

cout<<"Forwards: ";
for (int i=0; i<cnt; i++){
    cout<<setprecision(2)<< fixed;
    if (i == cnt - 1)
    {
        cout << arr[i];
    }
    else
    {
        cout << arr[i] << ", ";
    }
}
cout<<endl;
//printing backwards 
cout << "Backwards: ";
for (int i=cnt-1; i>=0; i--){
    cout<<setprecision(2)<< fixed;
    if (i == cnt + 1)
    {
        cout << arr[i];
    }
    else
    {
        cout << arr[i] << ", ";
    }

the forwards part comes out correct: 1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00

but the backwards is what prints out

10.00, 9.00, 8.00, 7.00, 6.00, 5.00, 4.00, 3.00, 2.00, 1.00,

how do I get rid of that last comma

Try something like this:

bool first_item = true;
for (unsigned int i = 0u; i < LIMIT; ++i)
{
    if (! first_item)
    {
        std::cout << ", ";
    }
    first_item = false;
    std::cout << number;
}
std::cout << "\n";

The above code fragment works regardless of the direction, ascending or descending.

The important part is the "flag" to determine if the first item has been printed.

In the forward-moving loop, if (i == cnt - 1) is checking if i is on the last element of the array.

In the backward-moving loop, you want to check if i is on the first element, but if (i == cnt + 1) will never be true for that check, as cnt+1 is out of bounds. The first element is at index 0, so use if (i == 0) instead:

cout << "Forwards: ";
cout << setprecision(2) << fixed;
for (int i = 0; i < cnt; ++i){
    if (i == cnt - 1){
        cout << arr[i];
    }
    else{
        cout << arr[i] << ", ";
    }
}
cout << endl;

cout << "Backwards: ";
cout << setprecision(2) << fixed;
for (int i = cnt-1; i >= 0; --i){
    if (i == 0){
        cout << arr[i];
    }
    else{
        cout << arr[i] << ", ";
    }
}
cout << endl;

Alternatively, print the 1st output value outside of the loop, and then start the loop on the 2nd output value:

cout << "Forwards: ";
cout << setprecision(2) << fixed;
cout << arr[0];
for (int i = 1; i < cnt; ++i){
    cout << ", " << arr[i];
}
cout << endl;

cout << "Backwards: ";
cout << setprecision(2) << fixed;
cout << arr[cnt-1];
for (int i = cnt-2; i >= 0; --i){
    cout << ", " << arr[i];
}
cout << endl;

Just write

if(i == 0)

instead of

if(i == cnt+1)

It will do the work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM