0

我无法对齐程序的输出。我想保持相同的名称并获得正确的间距。下面提供了代码。我也尝试过使用left,但它仍然无法正常工作。

我期待的输出:
预期的

我得到的输出:
得到

    //taking name and votes recieved
    for (i = 0; i < 5; i++)
    {
        cout << "Enter last name of candidate " << (i + 1) << ": ";
        cin >> names[i];
        cout << "Enter votes recived by " << names[i] << ": ";
        cin >> votes[i];
    }

    //calculating total votes
    for ( i = 0; i < 5; i++)
    {
        total = total + votes[i];
    }

    //calculating percentage of total votes for each candidate
    for ( i = 0; i < 5; i++)
    {
        percent_of_total[i] = (votes[i] / total) * 100.0;
    }

    //checking winner
    winner = names[0];
    int most = 0;

    for ( i = 0; i < 5; i++)
    {
        if (votes[i] > most)
        {
            most = votes[i];
            winner = names[i];
        }
    }

    cout << fixed << setprecision(2);

    //dislaying

    cout << "Candidte" << setw(20) << "Votes Recieved" << setw(20) << "% of Total Votes";

    for (i = 0; i < 5; i++)
    {
        cout << endl;
        
        cout << names[i] << setw(20) << votes[i] << setw(20) << percent_of_total[i];
    }

    cout << endl;

    cout << "Total" << setw(20) << total;

    cout << endl << "The winner of the Election is " << winner << ".";
    
    return 0;
}
4

1 回答 1

2

setw需要在您希望应用固定长度的字段之前调用。这包括名称。如果您想保持名称左对齐,您可以使用

std::cout << std::left << std::setw(20) << name /*<< [...]*/;

作为旁注,您应该避免使用using namespace std;. 原因是 std 包含很多名称,您可能会使用其他使用相同名称的库或自己使用它们。std 相当短,不会使代码过于混乱。一个可行的替代方法是使用

using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::left;
// etc

对于您要使用的所有名称。

另一种选择是在要使用 std 命名空间的函数中调用 using namespace std。

#include <iostream>

void f()
{
  using namespace std;
  cout << "f() call" << endl;
}

int main()
{
  // std not being used here by default
  f();
  return 0;
}
于 2020-12-15T11:35:25.470 回答