c++ - QTextStream 按点对齐(小数分隔符)

标签 c++ qt text qt5 c++14

我正在使用 QTextStream 将数据写入文件。它组织得很好(几乎完美),例如:

i           t           y          yy           
0   0.0166667   -0.649999     67.6666           
1   0.0333333    0.477777    -43.4444           
2        0.05   -0.246295     30.6295           
3   0.0666666    0.264197     -18.753           
4   0.0833333  -0.0483533     14.1687           
5         0.1    0.187791     -7.7791           
6    0.116667   0.0581394     6.85273           
7    0.133333    0.172351    -2.90181           
8        0.15    0.123988     3.60121           
9    0.166667    0.184008   -0.734136

以上内容由

制作
    stream <<  qSetFieldWidth(5)  << i
           <<  qSetFieldWidth(12) << t
           <<  qSetFieldWidth(12) << y
           <<  qSetFieldWidth(12) << yy
           << endl;

但我希望列按点(小数点分隔符)对齐,例如:

0   0.0166667   -0.649999     67.6666           
1   0.0333333    0.477777    -43.4444           
2   0.05        -0.246295     30.6295           
3   0.0666666    0.264197    -18.753           
4   0.0833333   -0.0483533    14.1687           
5   0.1          0.187791     -7.7791           
6   0.116667     0.0581394     6.85273           
7   0.133333     0.172351     -2.90181           
8   0.15         0.123988      3.60121           
9   0.166667     0.184008     -0.734136

我该怎么做?

最佳答案

您必须将数字分成整数部分(右对齐)和小数部分(左对齐)(并从小数表示形式中去除前导零)。

一种更简单的方法是用适合整数表示中数字位数的空格填充输出(也考虑符号)。

未经测试:

// inefficient, but illustrates the concept:
int NumIntDig(double x) {
    stringstream s;
    s << int(x);
    return s.str().size();
} 

stream <<  qSetFieldAlignment(AlignRight) << qSetFieldWidth(5)  << i
       <<  qSetFieldAlignment(AlignLeft) <<
       <<  qSetFieldWidth(4-NumIntDig(t)) << " "  
       <<  qSetFieldWidth(8+NumIntDig(t)) << t
       <<  qSetFieldWidth(4-NumIntDig(y)) << " "  
       <<  qSetFieldWidth(8+NumIntDig(t)) << y
       <<  qSetFieldWidth(4-NumIntDig(yy)) << " "  
       <<  qSetFieldWidth(8+NumIntDig(t)) << yy
       << endl;

关于c++ - QTextStream 按点对齐(小数分隔符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093193/

相关文章:

javascript - Golang中如何使用javascript获取特定网站元素或提交表单

c++ - 用常量变量定义替换问题

r - 从r中的字符串中提取单词

java - 为什么我的构造函数不能正常工作?

c# - 使用 MemoryMappedFile 将 2 个数组从 CreateFileMappingW 共享到 C#

c++ - 从 DLL 导出函数释放 CStringArray& 参数时出现堆冲突

c++ - 无法理解线路的工作原理

c++ - c/c++ 和 objective c ios

C++:传递给 C 运行时函数的参数无效

c++ - 相互比较文本文件的元素