如何将显示的数据与表格对齐?

时间:2016-09-04 21:32:45

标签: c++

我目前正在学习C ++。我要将文件中的数据读入下表。我能够读取数据但在表格中它不喜欢这样:

  

StdID A1 A2 A3

           

030302 9 5 6

而是

  

030302

     

9

     

5

     

6

     

如何将此格式正确地格式化到表格中?我试过setw但它没有解决问题。

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

int main()
{
  int StdID=0, A1=0, A2=0, A3=0;

  ifstream fin;
  fin.open("data.txt");
  if(!fin)
    cout << "The file does not exist.";
  else{
    cout << "Std-ID     A1     A2     A3     Min     Max     Avg\n";
    cout << " ---------------------------------------------------\n";
    while (!fin.eof())
      {
        fin >> StdID >> A1 >> A2 >> A3;
        cout << setw(10) << StdID << endl;
        cout << setw(10) << A1 << endl;
        cout << setw(10) << A2 << endl;
        cout << setw(10) << A3 << endl;
      }
  }



    return 0;
}

3 个答案:

答案 0 :(得分:2)

每次显示变量时,您也会显示一个新行(使用每个<< endl;)。

这应该有效:

while (!fin.eof())
  {
    fin >> StdID >> A1 >> A2 >> A3;
    cout << setw(10) << StdID << setw(10) << A1 << setw(10) << A2 << setw(10) << A3 << endl;

    // You may also break it down like this:
    //cout << setw(10) << StdID;
    //cout << setw(10) << A1;
    //cout << setw(10) << A2;
    //cout << setw(10) << A3 << endl; // one endl on each iteration
  }

建议:您可能需要学习Why is iostream::eof inside a loop condition considered wrong。更好地使用这个条件:

while (fin >> StdID >> A1 >> A2 >> A3)

修改

Tab键 \t仍可使用字符串,类似于此:

cout << "Std-ID\t\t\tA1\t\t\tA2\t\t\tA3\t\t\tMin\t\t\tMax\t\t\tAvg\n";

另外,您最好使用if (fin.is_open())来检查文件是否已成功打开。

答案 1 :(得分:1)

您正在使用<< endl在每个打印件上添加换行符。删除除最后一个之外的所有内容,它应该可以正常工作。

cout << setw(10) << StdID;
cout << setw(10) << A1;
cout << setw(10) << A2;
cout << setw(10) << A3 << endl;

或者你可以将它们全部组合成一行。

此外,您应该避免using namespace std。有关详细信息,请参阅this问题。

答案 2 :(得分:0)

在每个cout语句的末尾,你写下这个:

cout /*...*/ << endl; //<-- This creates a new line

每次你写这篇文章时,你都在创建一个新行。相反,只将它保留在最后一行,或将所有语句放在同一行上。 也:

while (!fin.eof())
  {
    fin >> StdID >> A1 >> A2 >> A3;
    cout << setw(10) << StdID << endl;
    cout << setw(10) << A1 << endl;
    cout << setw(10) << A2 << endl;
    cout << setw(10) << A3 << endl;
  }

可以简化为:

while (fin >> StdID >> A1 >> A2 >> A3)
  {
    cout << setw(10) << StdID << endl;
    cout << setw(10) << A1 << endl;
    cout << setw(10) << A2 << endl;
    cout << setw(10) << A3 << endl;
  }