首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对输入流使用setw()

如何对输入流使用setw()
EN

Stack Overflow用户
提问于 2021-09-22 18:53:37
回答 2查看 85关注 0票数 0

我知道有些人会说这个问题是重复的,但我真的找不到一个有用的答案。

假设我有以下程序:

代码语言:javascript
复制
#include <iostream>
#include <string>
using std::cout;

int main(){
    std::string something;
    cout<<"Type something";
    std::cin>>something;
}

如何使用setw()使输出看起来像这样?

代码语言:javascript
复制
Type something "then after some whitespaces for example 10 the user will start typing"

我尝试在输出中使用setw()

代码语言:javascript
复制
 #include <iostream>
 #include <string>
 #include <iomanip>
 using std::cout;

 int main(){
    std::string something;
    cout<<std::left<<std::setw(24)<<"Type something";
    std::cin>>something;
}

预期输出应该是:

实际输出为:

EN

回答 2

Stack Overflow用户

发布于 2021-09-22 19:40:37

我不能复制你说的,你给works fine for me看的代码。

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <iomanip>

int main(){
    std::string something;
    std::cout << std::left << std::setw(24) << "Type something"; // prints "Type something          "
    std::cin >> something;
    return 0;
}

也就是说,您可以简单地输出一个包含所需空格数量的字符串:

代码语言:javascript
复制
#include <iostream>
#include <string>

int main(){
    std::string something;
    std::cout << "Type something          ";
    // alternatively:
    // std::cout << "Type something" << std::string(10, ' ');
    std::cin >> something;
}
票数 1
EN

Stack Overflow用户

发布于 2021-09-22 19:34:28

一种可能的解决方案是在setw之后使用任何特殊字符

示例代码:

代码语言:javascript
复制
int main()
{
    std::string something;
    cout<< "Type something" << setw(24) << ":";
    std::cin>>something;
}

输出:

Type something :inputString

参考文献:

iomanip setw() function in C++ with Examples

Setw C++: An Ultimate Guide to Setw Function

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69289814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档