[英]Why is setw not showing spaces?
I have this code.我有这个代码。 It works for the first space, but it doesn't work for the second one.
它适用于第一个空间,但不适用于第二个空间。 Can anyone tell me why, or how to fix it?
谁能告诉我为什么,或者如何解决?
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
//Constants
const int LENGTH_SPACE = 10;
const int LENGTH_SPACES = 2;
//Structs
struct post_t
{
int authorID;
int targetID;
string message;
};
void displayStruct(post_t &demo)
{
cout << demo.authorID << setw(LENGTH_SPACE) << demo.targetID << setw(LENGTH_SPACES) << demo.message << endl;
};
int main() {
post_t demo = {101, 9999, "Just a test"};
displayStruct(demo);
return 0;
}
EXPECTED OUTPUT预期 OUTPUT
101 9999 Just a test
You seem to expect setw(LENGTH_SPACE)
to simply add spaces in between the other output.您似乎希望
setw(LENGTH_SPACE)
在其他 output 之间简单地添加空格。
For that you would not need setw
(see below).为此,您不需要
setw
(见下文)。 What it does instead ( cppreference ):它做了什么( cppreference ):
When used in an expression out << setw(n) or in >> setw(n), sets the width parameter of the stream out or in to exactly n.
在表达式 out << setw(n) 或 in >> setw(n) 中使用时,将 stream 的宽度参数设置为 out 或 in 正好为 n。
For example this:例如这个:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::setw(5) << "123" << "\n";
std::cout << "^^ two spaces added to a 3 characters long output\n";
}
produces output:生产 output:
123
^^ two spaces added to a 3 characters long output
And output of this:和 output 这个:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::setw(2) << "123" << "\n";
std::cout << "no space added when the length of the string is longer than the requested width\n";
}
is是
123
no space added when the length of the string is longer than the requested width
If you simply want a certain number of spaces ' '
in between the output of the members of the struct, thats not what setw
does.如果您只是想要结构成员的 output 之间有一定数量的空格
' '
,那不是setw
所做的。 Instead:反而:
std::cout << "a" << std::string(number_of_spaces,' ') << "b";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.