c++ - 为什么 setw 不显示空格?
问题描述
我有这个代码。它适用于第一个空间,但不适用于第二个空间。谁能告诉我为什么,或者如何解决?
#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;
}
预期输出
101 9999 Just a test
解决方案
您似乎希望setw(LENGTH_SPACE)
在其他输出之间简单地添加空格。
为此,您不需要setw
(见下文)。它做了什么(cppreference):
当在表达式 out << setw(n) 或 in >> setw(n) 中使用时,将流输出或输入的宽度参数设置为正好 n。
例如这个:
#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";
}
产生输出:
123
^^ two spaces added to a 3 characters long 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";
}
是
123
no space added when the length of the string is longer than the requested width
' '
如果您只是想要在结构成员的输出之间有一定数量的空格,那不是什么setw
。反而:
std::cout << "a" << std::string(number_of_spaces,' ') << "b";
推荐阅读
- netlogo - 代理死亡肯定会影响代理正在运行的“while”循环吗?
- javascript - Filter multiple pokemons of PokeApi
- google-sheets - Copy value from a cell to the rest of a colum
- c# - Sending email to multiple recipients fails
- flutter - When I press the card how to set card data into text field in flutter
- laravel - Custom login property Laravel 8
- php - Get week range with timezone
- python - Pygame window closes right after
- kubernetes - Is there any way to know when a PVC is mounted last time in k8s?
- flutter - how to solve "Execution failed for task ':app:compileFlutterBuildDebug"