c++setw

Can't align properly using setw manipulator


I can't align the output of my program. 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.

The output I am expecting:
expected

The output I am getting:
getting

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

Solution

  • setw needs to be invoked before the field you wish to apply the fixed length to. 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;. 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 is fairly short and doesn't clutter up the code too much. 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.

    #include <iostream>
    
    void f()
    {
      using namespace std;
      cout << "f() call" << endl;
    }
    
    int main()
    {
      // std not being used here by default
      f();
      return 0;
    }