简体   繁体   English

使用 setw 操纵器无法正确对齐

[英]Can't align properly using setw manipulator

I can't align the output of my program.我无法对齐我的程序的 output。 I want to keep the same names and get the right spacing.我想保持相同的名称并获得正确的间距。 The code is provided below.下面提供了代码。 I also tried using left but it still does not work.我也尝试过使用left ,但它仍然不起作用。

The output I am expecting:我期待的 output:
预期的

The output I am getting: output 我得到:
得到

    //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;
}

setw needs to be invoked before the field you wish to apply the fixed length to. setw需要在您希望应用固定长度的字段之前调用。 That includes the names.这包括名称。 If you want to keep the names left aligned you can use如果您想保持名称左对齐,您可以使用

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

As a side note you should avoid using using namespace std;作为旁注,您应该避免使用using namespace std; . . The reason is that std contains a lot of names and you might use other libraries using the same names or use them yourself.原因是 std 包含很多名称,您可能会使用其他使用相同名称的库或自己使用它们。 std is fairly short and doesn't clutter up the code too much. std 相当短,不会使代码过于混乱。 A viable alternative is to use一个可行的替代方法是使用

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

for all the names you want to use.对于您要使用的所有名称。

another alternative is to invoke using namespace std in the function you want to use the std namespace.另一种选择是在您想要使用 std 命名空间的 function 中调用 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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