hi i am trying to use setw with a string..
here is my code..

string a="hello";
cout<<setw(10)<<a;

i inserted string header and iomanip header files...

now my output should be with a few number of blank spaces and then it should print hello..
but its not working for me...
could you pls help me out!!
thanks in advance!!

Recommended Answers

All 8 Replies

In what way is it not working? The same code works ok for me.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main() {
    string a = "hello";
    cout<<"|"<< setw(10) << a <<"|"<<endl;
}

#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
int main()
{
float a=3.141567;
string b="hello";
cout<<"|"<<setw(10)<<b<<"|"<<endl;
cout<<"|"<<setw(10)<<a<<"|"<<endl;

}

i am getting the output as:
|hello**************|
|*****3.141567|
the * represents the blank spaces...
i dont understand why the spaces are coming after the string but while displaying the floating point the blank spaces are coming before the number... and there is also difference in the length of blank spaces

This is interesting. I do not see the same problem with your code on my compiler. What compiler are you using? If you break down the operations, does it still not work?

#include<iostream>
#include<iomanip>
#include<string>

using namespace std;

int main() {
    float a=3.141567;
    string b="hello";
    cout<<"|";
    cout.width(10); // strip out the setw()
    cout<<b<<"|"<<endl;
    cout<<"|"<<setw(10)<<a<<"|"<<endl;
}

i dont understand it...
i am still getting the same output...
i am using GNU compiler...

I read about an older bug in the GNU compiler where C++ strings did not work with setw(), but string constants did. Does this work for you?

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    char const* a = "hello";
    cout<<"|"<< setw(10) << a <<"|"<<endl;
}

thanks a lot.. it works now...
the output is:
|*******hello|
|***3.141567|
but the length of blank spaces differ..

I don't understand. The number of spaces should be different because the "hello" and "3.141567" are different lengths. The spaces are padding within the specified field width of 10, they fill in what the strings do not.

thank u for your help:))))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.