在C ++中使用setw对齐输出列

时间:2020-02-28 00:54:01

标签: c++ text-alignment setw

我一直在阅读有关setw的列宽的信息,但是为每个列设置宽度似乎并没有使最后两列对齐。我尝试使用右对齐,但是它也更改了左两列的对齐方式,这是我不想要的。最后,我希望一切保持一致。除了setw之外,还有其他更简单的方法吗?

当前代码:

void print_head()
{
  cout.setf(ios::left);
  cout << setw(16) << "Operation" 
       << setw(32) << "z" 
       << setw(8) << "Cost" 
       << setw(8) << "Total" << endl;

  for (int i=0; i<64; ++i) cout << "-";
  cout << endl;
}

print_head();
cout.setf(ios::left);
cout << setw(16) << "Initial String" 
    << setw(32) << test1 
    << setw(8) << "0" 
    << setw(8) << "0" << endl;
for (int g = minops[0] + minops[1] - 1;g>-1;g--){
    string a;
    for(stringstream ss(operations[g]); getline(ss, a, ','); )  // that's all ! 
        v.push_back(a);

    //cout << v[current] << "\n";
    if (v[current] == "c"){
        z = sright(z, cursorg);
        current++;
        cout << setw(16) << "right" 
            << setw(32) << z
            << setw(8) << "0" 
            << setw(8) << tcost << endl;
    }else if (v[current] == "d"){
        z = sdelete(z, cursorg);
        size = size - 1;
        tcost = tcost + 2;
        cout << setw(16) << "delete" 
            << setw(32) << z
            << setw(8) << "2" 
            << setw(8) << tcost << endl;
        //cout << "cursor out of delete: " << cursorg << "\n";
        current = current + 2;
    }else if (v[current] == "r"){
        z = sreplace(z, cursorg, test2, stoi(v[current+1]), stoi(v[current+2]));
        int printtemp = stoi(v[current+2]);
        string s(1,test2[printtemp]);
        string tempstr = "replace by " + s;
        tcost = tcost + 4;
        cout << setw(16) << tempstr
            << setw(32) << z
            << setw(8) << "4" 
            << setw(8) << tcost << endl;
        current = current + 3;
    }else if (v[current] == "i"){   
        z = sinsert(z, test2, cursorg, stoi(v[current+1]));
        size = size - 1;
        tcost = tcost + 3;
        int printtemp = stoi(v[current+1]);
        string s(1,test2[printtemp]);
        string tempstr = "insert " + s;
        cout << setw(16) << tempstr
            << setw(32) << z
            << setw(8) << "3" 
            << setw(8) << tcost << endl;
        current = current + 2;
    }else{

    }

    //cout << operations[g] << "\n";
    //cout << "z is: " << z << "\n";

}
cout << "\n";
cout << "minimum operations is: " << minops[0] << "\n";

这是我当前的输出,但是我希望成本和总成本成为标题下整齐的对齐列。如何使用setw修复对齐方式?

This is my current output

删除实现:

string sdelete(string input, int &cursor){ //deletes the letter under the cursor, cost 2
    if (cursor == (input.length() + 1)){
        //do nothing
    }else{
        input[cursor] = NULL;
        cursor = cursor+1;
    }
    //DEBUG cout << "delete input: " << input << "\n";
    //DEBUG cout << "cursor in delete: " << cursor << "\n";

    return input;
}

0 个答案:

没有答案