【问题标题】:How can I use setw() with input stream [closed]如何在输入流中使用 setw() [关闭]
【发布时间】:2021-11-16 06:00:59
【问题描述】:

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

假设我有以下程序:

#include <iostream>
#include <string>
using std::cout;

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

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

Type something "then after some whitespaces for example 10 the user will start typing"

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

 #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;
}

预期的输出应该是:

实际输出为:

【问题讨论】:

  • 在你的输出中使用setw,而不是你的输入。
  • @NathanOliver 我尝试使用 cout
  • 请向我们展示您的尝试。到目前为止,您显示的代码显示没有使用 setw。它甚至不包括iomanip
  • @Chris 我编辑了你现在可以看到的代码
  • @Seba Can't reproduce,你展示的代码对我来说很好用。

标签: c++ setw


【解决方案1】:

我无法重现你所说的,你显示的代码works fine for me

#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;
}

也就是说,您可以简单地输出具有所需空格数的字符串:

#include <iostream>
#include <string>

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

【讨论】:

  • 感谢您的信息,但是当我运行代码时,如果我使用 std::string(10,' '),用户输入会在打印的消息之后直接开始
  • 我希望用户在特定数量的空白之后开始输入,如果我需要大量空白,仅在 cout 语句中使用空格是低效的
  • @Seba 鉴于显示的代码,您声称在物理上是不可能的。所以你必须做一些与你展示的不同的事情。
【解决方案2】:

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

示例代码:

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

【讨论】:

  • Type something 和他们输入的输入之间的空格。这不会那样做。
猜你喜欢
  • 2017-07-20
  • 1970-01-01
  • 2012-07-01
  • 2021-06-26
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多