Format questions

I'm curious to why when using functions to call a file. one uses ostream& and not ofstream& - although both methods seem to work and make no visual change to the outcome.

When using setw()<<left/right - why is it at times when I use this the output isn't doing what i've set it to do? IE i'll put in <<right and it still aligned left.

ofstream and ostream are interchangeable. Ofstream came from ostream to begin with.

For setw(), are you using it like this?:

http://www.cplusplus.com/reference/iomanip/setw/
zapshe wrote:
ofstream and ostream are interchangeable.

They are certainly not "interchangeable".
An ofstream is a ostream, but an ostream is not an ofstream.

@CodeNovice01, Just saying "when I do this thing why isn't it doing what I want" is a pretty vague question. Make a little example program that shows exactly what you are doing. Clearly state what you want it to do and what it is doing.

The main problem with setw is that it only applies to the next thing (that actually prints something) after the <<.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    // default is right-justified
    cout << '|' << setw(20) << "hello" << "world|\n";

    cout << '|' << left << setw(20) << "hello" << "world|\n";

    // we usually want numbers to be right-justified
    cout << '|' << right << setw(10) << 1234 << "|\n";

    cout << '|' << left << setw(10) << 1234 << "|\n";
}
Last edited on
> I'm curious to why when using functions to call a file. one uses ostream& and not ofstream& -
> although both methods seem to work and make no visual change to the outcome.

Writing functions in terms of generic streams offers greater flexibility.
For instance, we can test our code using string streams and/or standard streams.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream> // we would use file streams in the actual program
#include <sstream>

// read up to 1000 integers from an input stream and write their sum to an output stream
bool write_integer_sum( std::istream& istm, std::ostream& ostm )
{
    long long sum = 0 ;

    int number ;
    int cnt = 0 ;
    for( ; cnt < 1000 && istm >> number ; ++cnt ) sum += number ;

    ostm << "sum of " << cnt << " numbers == " << sum << '\n' ;

    return ostm.good() ;
}

int main() // minimal test driver
{
    std::istringstream test_stm( "12 34 56 78 21 0 31 42 -99 56 -7\n" ) ;
    if( write_integer_sum( test_stm, std::cout ) ) std::cout << "ok\n" ;
}

http://coliru.stacked-crooked.com/a/d7def141e8bf3371
Topic archived. No new replies allowed.