Domanda

Come si fa a "posizionato in modo assoluto" colonne con cout, che leftaligns numeri testo e allineato a destra?

#include <iostream>
#include <iomanip>
using namespace std;

struct Human {
    char name[20];
    char name2[20];
    char name3[20];
    double pts;
};

int main() {
    int i;
    Human myHumen[3] = {
        {"Mr", "Alan", "Turing", 12.25},
        {"Ms", "Ada", "Lovelace", 15.25},
        {"Sir",  "Edgar Allan", "Poe", 45.25}
    };
    cout << "Name1" << setw(22) << "Name2" << setw(22) << "Name3" << setw(22) << "Rating" <<endl;
    cout << "-----------------------------------------------------------------------\n";
    for(i = 0; i < 3; i++) {
        cout << myHumen[i].name << setw(22) << myHumen[i].name2 << setw(22) << myHumen[i].name3 << setw(20) << myHumen[i].pts << endl;
    }//this didn't do nice printouts, with leftalign for text and rightalign with numbers
}
È stato utile?

Soluzione

Si utilizzano le e manipolatori "sinistra" e "destra":

cout << std::left  << std::setw(30) << "This is left aligned"
     << std::right << std::setw(30) << "This is right aligned";

Un esempio di testo + numeri:

typedef std::vector<std::pair<std::string, int> > Vec;
std::vector<std::pair<std::string, int> > data;
data.push_back(std::make_pair("Alan Turing", 125));
data.push_back(std::make_pair("Ada Lovelace", 2115));

for(Vec::iterator it = data.begin(), e = data.end(); it != e; ++it)
{
    cout << std::left << std::setw(20) << it->first
         << std::right << std::setw(20) << it->second << "\n";
}

che stampa:

Alan Turing                          125
Ada Lovelace                        2115

Altri suggerimenti

Questo sta per essere un po 'impopolare, ma si può solo usare printf per questo tipo di programma rapido. Le stringhe di formattazione sono più facili da capire e da usare (dato qualcuno che sia groks iostreams e printf).

#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>

struct Human {
  char name[20];   // consider using std::string
  char name2[20];
  char name3[20];
  double pts;
};

int main() {
  using namespace std;
  Human people[3] = {
    {"Mr", "Alan", "Turing", 12.25},
    {"Ms", "Ada", "Lovelace", 15.25},
    {"Sir",  "Edgar Allan", "Poe", 45.25}
  };
  printf("%-22s%-22s%-22s%20s\n", "Name1", "Name2", "Name3", "Rating");
  cout << string(22 * 3 + 20, '-') << '\n';
  for (int i = 0; i < 3; i++) {
    Human const& h = people[i];
    printf("%-22s%-22s%-22s%20f\n", h.name, h.name2, h.name3, h.pts);
  }
  return 0;
}

E 'sicuro (per impostazione predefinita, vedere std :: sync_with_stdio) per miscelare cout e printf, e un buon compilatore può controllare i tipi di stringhe di formato anche per te (-Wall in gcc).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top