C++ 字符串格式 - 固定宽度的 float ,以及在偏移量处带有空格的字符串

标签 c++

我正在使用 stringstreams,我有这样一行:

10 651.23 Some longer name

我想将它提取到 uint、double 和字符串中,例如 10、651.23、“Some longer name”

我试过了

    iss >> quantity >> price >> std::noskipws >> name;

但似乎并没有看上去那么容易。如何获取字符串的其余部分(包括空格)?

稍后我想显示带有前导字符和固定精度的 float :

    std::cout << std::setprecision(2) << std::fixed << std::setw(7) << std::setfill('.') << price;

然而,当我使用 std::fixed 时,我的填充和宽度被拒绝了。如何解决?

谢谢

当前代码:

std::string filename;

std::ifstream is;
do {

    std::cout << "Podaj nazwę pliku do wczytania: " << std::endl;
    std::cin >> filename;
    is.open(filename.c_str());

    if(is.good()) break;
} while(true);

std::string name;
std::string wtf;
unsigned int quantity = 0;
double price = 0;
unsigned int i = 1;

while(is >> quantity >> price >> std::ws && std::getline(is, name)) {
    std::cout << "| ";
    std::cout << std::setw(2) << i++ << " | ";
    std::cout << std::setw(30) << std::setfill('.') << name << " | ";
    std::cout << std::setw(3) << std::setfill(' ') << quantity << " x ";
    std::cout << std::setprecision(2) << std::setw(10) << std::setfill(' ') << std::fixed << price << " zl | ";
    std::cout << std::setw(11) << std::setfill(' ') << quantity * price << " zl |";
    std::cout << std::endl;
}

文件看起来像:

10 12999 TV55AA8000 smarttv ultra HD
5 12990 TV55AB600 smarttv ultraHD
20 9999 TV55GD2340s smarttv
10 7999 TV463400 funkcja 3D
20 1699.5 telewizor super!
30 1400 telewizor 3d 1000Hz
20 12999 telewizor nr 1
30 12000 EE55650 smarttv
10 1000 ED325400s
10 14350.00 EE80234
5 5600.00 TV60ED23231 smart tv plazma
10 2000.00 TV320323
1 12999.00 TV66EE231231 smarttv
12 3400.00 TV4243dss 3D

最佳答案

您可以尝试将 std::setw(7) << std::setfill('.') << std::fixed 之前的操纵器机械手

std::cout << std::setprecision(2) << std::setw(7) << std::setfill('.') 
          << std::fixed << price;

但至于标准定义,这并不重要。
看起来这可能是您的实际工具链的错误。

关于C++ 字符串格式 - 固定宽度的 float ,以及在偏移量处带有空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24109817/

相关文章:

c++ - 返回局部变量的 std::move

c++ - 在 C++ 中实例化一个新对象

c++ - C++ STL 中的 BFS 图遍历

c++ - 我正在尝试将 int 转换为 char 并输出 ascii 值?

C++ void 作为函数调用的前缀。例如。 `main() {void func();}`

c++ - 赋值运算符 "required"是否要返回?

c++ - 结构静态成员含义/定义

c++ - 我如何开始使用 boost

c++ - 带有自定义分配器的 const T 的 STL 容器是否格式错误?

c++ - 将重复的元素分开