0

I know some people will say this question is repeated but I really couldn't find a useful answer.

Let's say I have the following program:

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

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

How can I use setw() so the output will look like this?

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

I tried to use setw() in output:

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

The expected output was supposed to be:

image

The actual output is:

image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Seba
  • 21
  • 8

2 Answers2

1

I can't reproduce what you say, the code you have showed 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;
}

That said, you could simply output a string with the desired number of spaces:

#include <iostream>
#include <string>

int main(){
    std::string something;
    std::cout << "Type something          ";
    // alternatively:
    // std::cout << "Type something" << std::string(10, ' ');
    std::cin >> something;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thanks for the information but still when I run the code the user input starts directly after the printed messege if I use std::string(10,' ') – Seba Sep 22 '21 at 19:47
  • I want the user to start typing after a specific amount of whitespace and it's inefficient to just use spaces in cout statement if I need a large number of whitespaces – Seba Sep 22 '21 at 19:49
  • @Seba what you claim is physically impossible given the code shown. So you must be doing something different than what you showed. – Remy Lebeau Sep 22 '21 at 20:03
0

One possible solution might be using any special character after setw

Sample Code:

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

Output:

Type something :inputString

References:

iomanip setw() function in C++ with Examples

Setw C++: An Ultimate Guide to Setw Function

Md. Faisal Habib
  • 1,014
  • 1
  • 6
  • 14