473,597 Members | 2,375 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

seeking within ostringstream's

What is a stringsteam supposed to do when you seek past the end of
existing buffer. I can seek past the end of a file stream (my
implementation fills the space will nulls but I cannot find if this is
guaranteed either)

Below code fails for a stringstream. Any good ways of dealing with
this.

Reason for doing this is that I am modify old C code for screen output
that positions fields based on a row. I wanted to use a stringstream
and just seek to the correct place.

I have tried basically filling the stream with X spaces first. But
then I am never sure there is enough space.

Any help appreciated.

Adrian

#include <iostream>
#include <sstream>
#include <fstream>

int main(int argc, char *argv[])
{
std::ofstream out("test.txt") ;

out.seekp(500);
out << "some text\n";

std::ostringstr eam out2;

out2.seekp(500) ;
out2 << "some text\n";

if(!out2)
{
std::cout << "bad out2\n";
}
return 0;
}

Sep 13 '07 #1
7 3101

Adrian <nn**@bluedream er.comwrote in message...
What is a stringsteam supposed to do when you seek past the end of
existing buffer. I can seek past the end of a file stream (my
implementation fills the space will nulls but I cannot find if this is
guaranteed either)

Below code fails for a stringstream. Any good ways of dealing with
this.

Reason for doing this is that I am modify old C code for screen output
that positions fields based on a row. I wanted to use a stringstream
and just seek to the correct place.

I have tried basically filling the stream with X spaces first. But
then I am never sure there is enough space.

Any help appreciated.
Adrian

#include <iostream>
#include <sstream>
#include <fstream>

int main(int argc, char *argv[]){
std::ofstream out("test.txt") ;

out.seekp(500);
out << "some text\n";

std::ostringstr eam out2;

out2.seekp(500) ;
if( not out2 ){
std::cout << "out2 in failure\n";
}
else{
std::cout << "out2 position=" <<out2.tellp()< <'\n';
}
out2 << "some text\n";

if(!out2)
{
std::cout << "bad out2\n";
}
return 0;
}
Your result?

--
Bob R
POVrookie
Sep 13 '07 #2
On Sep 13, 12:40 pm, "BobR" <removeBadB...@ worldnet.att.ne twrote:
Below code fails for a stringstream. Any good ways of dealing with
this.
Your result?
The stringstream is not in a good state. I tried it with exceptions on
and I get
"basic_ios::cle ar" from what()
Sep 13 '07 #3

Adrian <nn**@bluedream er.comwrote in message...
On Sep 13, 12:40 pm, "BobR" wrote:
Below code fails for a stringstream. Any good ways of dealing with
this.
Your result?

The stringstream is not in a good state. I tried it with exceptions on
and I get
"basic_ios::cle ar" from what()
I think a safer way to move to a position might be:

std::ostringstr eam out2;
// ....

size_t pos( out2.tellp() );
std::string Space( ( 500 - pos ), ' ' );

// out2.seekp(500) ;
out2<<Space;

// ....

--
Bob R
POVrookie
Sep 13 '07 #4
On Sep 13, 7:05 pm, Adrian <n...@bluedream er.comwrote:
What is a stringsteam supposed to do when you seek past the end of
existing buffer. I can seek past the end of a file stream (my
implementation fills the space will nulls but I cannot find if this is
guaranteed either)
I can't find anything really specifying it either, but I suspect
that it's undefined behavior (or unspecified). It also depends
on whether you are using the two argument form of seek, or the
one argument form. (With the one argument form, it's actually
impossible to obtain a position which you haven't already
visited without involving undefined or unspecified behavior.
With the possible exception of start of file.)

Logically, one might say that a good implementation would
generate an error on an attempt to seek beyond end of file, but
in practice, this would have significant run-time cost on some
systems.
Below code fails for a stringstream. Any good ways of dealing with
this.
Reason for doing this is that I am modify old C code for
screen output that positions fields based on a row. I wanted
to use a stringstream and just seek to the correct place.
I have tried basically filling the stream with X spaces first.
But then I am never sure there is enough space.
#include <iostream>
#include <sstream>
#include <fstream>
int main(int argc, char *argv[])
{
std::ofstream out("test.txt") ;
out.seekp(500);
The above line is not even guaranteed to compile, much less do
anything useful.
out << "some text\n";
std::ostringstr eam out2;
out2.seekp(500) ;
And the same holds true here.
out2 << "some text\n";
if(!out2)
{
std::cout << "bad out2\n";
}
return 0;
}
I'm not too sure what you're doing, but it sounds like what you
want is something like std::string or std::vector<cha r>, using
resize( ' ' ) as needed.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Sep 14 '07 #5
On Sep 14, 3:34 am, James Kanze <james.ka...@gm ail.comwrote:
I'm not too sure what you're doing, but it sounds like what you
want is something like std::string or std::vector<cha r>, using
resize( ' ' ) as needed.
I am trying to clean up and rewrite some old code that is creating
rows for screen display that uses cursor position and printf type
args.

Thing is I can never tell exactly how long the row could be. And the
version of snprintf on this platform returns -1 if printed string is
longer then buffer rather then what should be then length.

I was hoping with seeking in a stringstream I could keep almost the
same arguments

Example of old stuff below:
pn1(0, row, "%-10s", HemName_of(obj) );
pn1(11, row, "%-2s",
Area_sh_nms[Mt_AreaFromCnum (Mt_Cnum_of(obj ))]);
pn1(14, row, "%-8d", Mt_Cnum_of(obj) );
pn1(23, row, "%-6s", Mt_ObjTypeName_ of(obj));
pn1(30, row, "%-7s", Mt_CmdtyName_of (obj));
if (Mt_ObjType_of( obj) == EQUITY_TYPE)
pn1(38, row, "%-25s", Mt_Name_of(obj) );
else {
strcpy(XSymb, Mt_Name_of(obj) );
if (strlen(XSymb) 14) {
XSymb[14] = '*';
XSymb[15] = '\0';
}
pn1(38, row, "%-15s", XSymb);
}
if (Mt_ObjType_of( obj) == FUTURE_TYPE)
{
pn1(54, row, "%-.6ld", Mt_dtoymd(Mt_Ex pDate_of(obj))) ;
pn1(62, row, "%-6s",
HemName_of(Mt_F indByLdOptIndx( Mt_RelLdOpt_of( obj))));
}
else if (Mt_ObjType_of( obj) == BOND_TYPE)
{
pn1(54, row, "%-.6ld", Mt_dtoymd(Mt_Ex pDate_of(obj))) ;
pn1(62, row, "%-6s", Mt_SymAlias_of( obj));
}
if (((Mt_ObjType_o f(obj) == FX_TYPE) ||
(Mt_ObjType_of( obj) == CASH_VOL_TYPE))
&& (Mt_HeFlags_of( Mt_Cmdty_of(obj )) & CASH_SCALE_MSK) )
{
pn1(69, row, "%-7s", Display_scale_o f(Mt_CshScale_o f(obj)));
}
else
pn1(69, row, "%-7s", Display_scale_o f(Mt_Scale_of(o bj)));
pn1(77, row, "%-3s", TransExchangeNa me(obj));
if (Mt_ObjType_of( obj) == BOND_TYPE)
{
if ((Mt_HeFlags_of (obj) & ALIAS_MSK) != 0)
pn1(76, row, "%c", 'A');
}
break;

Sep 14 '07 #6

Adrian <nn**@bluedream er.comwrote in message...
>
I am trying to clean up and rewrite some old code that is creating
rows for screen display that uses cursor position and printf type
args.

Thing is I can never tell exactly how long the row could be. And the
version of snprintf on this platform returns -1 if printed string is
longer then buffer rather then what should be then length.
size_t rows(25);
size_t cols(80);
std::vector<std ::stringvScrn( rows, std::string( cols, ' ' ) );

So, now you have an 25x80 "screen". But, now you can change it's size at
will.

// add a row
vScrn.push_back ( std::string( cols, ' ' ) );

// make all cols 90
for( size_t i(0); i < vScrn.size(); ++i ){
vScrn.at(i).app end( 10, ' ' ); // add 10 spaces
} // for(i)

// make it 20x50
vScrn.resize( 20 );
for( size_t i(0); i < vScrn.size(); ++i ){
vScrn.at(i).res ize( 50 );
} // for(i)

// Change the char at row 3, col 22, to "A":
vScrn.at(2).at( 21 ) = 'A';

// send the whole thing to cout:
std::copy( vScrn.begin(), vScrn.end(),
std::ostream_it erator<std::str ing>( std::cout, "\n" ) );

Etc..

You could put it all in one std::string, but then you'd need to keep track
of the new-line chars ('\n').
std::string( " line one.\n line two.\n line three.\n ....." );

I much prefer the vector of strings. Use the power of the standard C++
library.
>
I was hoping with seeking in a stringstream I could keep almost the
same arguments
For a learning excersize, go ahead. Otherwise, re-design it from the ground
up. I'm still fighting an C_to_C++ project I started years ago, a real mess.
(if only I knew then what I know now! <G>).
>
Example of old stuff below:
pn1(0, row, "%-10s", HemName_of(obj) );
Without knowing what declaration of 'pn1' is, it's hard to give you an
example.

Think it over, and come back here if/when you need help.

--
Bob R
POVrookie
Sep 14 '07 #7
Adrian wrote:
On Sep 14, 3:34 am, James Kanze <james.ka...@gm ail.comwrote:
I'm not too sure what you're doing, but it sounds like what you
want is something like std::string or std::vector<cha r>, using
resize( ' ' ) as needed.
I am trying to clean up and rewrite some old code that is creating
rows for screen display that uses cursor position and printf type
args.
But that doesn't really tell me much. The obvious way to
represent rows in a screen display would be something like:
typedef std::vector< char Row ;
std::vector< Row display ;
Thing is I can never tell exactly how long the row could be. And the
version of snprintf on this platform returns -1 if printed string is
longer then buffer rather then what should be then length.
What I'd probably do is use something like the above. Then,
given a request to insert an int 'value' at position i, j, I'd
write something like:

std::ostringstr eam tmp ;
tmp << value ;
if ( display.size() <= i ) {
display.resize( i + 1 ) ;
}
Row& r = display[ i ] ;
std::string s( tmp.str() ) ;
size_t lastCol = j + s.size() ;
if ( r.size() <= lastCol ) {
r.resize( lastCol + 1, ' ' ) ;
}
std::copy( s.begin(), s.end(), r.begin() + j ) ;
I was hoping with seeking in a stringstream I could keep almost the
same arguments
Example of old stuff below:
pn1(0, row, "%-10s", HemName_of(obj) );
pn1(11, row, "%-2s", Area_sh_nms[Mt_AreaFromCnum (Mt_Cnum_of(obj ))]);
pn1(14, row, "%-8d", Mt_Cnum_of(obj) );
pn1(23, row, "%-6s", Mt_ObjTypeName_ of(obj));
pn1(30, row, "%-7s", Mt_CmdtyName_of (obj));
The only real problem will be handling the formatting strings.
And it shouldn't be too difficult to parse them, mapping them to
fmtflags, width and precision arguments for the ostringstream.
Or check out boost::format, which I think can handle about 95%
of the formatting flags---only a few of the more exotic cases
aren't handled. (The syntax of boost::format is rather wierd,
since it uses %, rather than <<, as the inserter, which rapidly
leads to fairly unreadable code. But if you're only inserting
one value at a time, and that value is always a parameter to the
function, it shouldn't be too bad. I used to have a Format
class myself; as a result of a challenge, I'd actually
implemented 100% of the printf formatting, plus the X/Open
extensions, along with all sorts of hooks to make it easy for
user defined types to do as well, if they had semantics more or
less like those of a floating point or integral number. I
stopped maintaining it sometime back, however, because I never
used it; the ostream formatting is so much more readable.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Sep 15 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
6195
by: Alex Vinokur | last post by:
Is it possible to use vector<ostringstream> ? Here is what I have got. =========================================== Windows 2000 CYGWIN_NT-5.0 1.3.22(0.78/3/2) GNU gcc version 3.2 20020927 (prerelease) ===========================================
6
3010
by: Eric Boutin | last post by:
Hi ! I have a strange problem with a std::ostringstream.. code : #include <sstream> /*...*/ std::ostringstream ss(); ss << "\"\"" << libpath << "\"\" \"\"" << argfilename << "\"\" \"\"" << outfilename << "\"\""; //line 75
5
2356
by: Simon Pryor | last post by:
I am having some strange problems using std::ostringstream. The simple stuff works okay, but trying to use: std::ostringstream::str(const std::string&) or: std::ostringstream::ostringstream(const std::string&) Gives some weird results on both Solaris & Linux. Either that or I'm missing something. I've made a simple program to
3
5595
by: Mathieu Malaterre | last post by:
Hello, I am trying to write this simple code: std::ostringstream s; s << 1024; std::cout << s.str() << std::endl; s.str(""); // <- problem s << 512; std::cout << s.str() << std::endl;
3
11108
by: Kyle Kolander | last post by:
I posted this in response to a previous thread but have not gotten any replies back... Hopefully someone has an answer? From looking at sections 27.7.3.2 and 27.7.1.2 of the standard, it appears str("") does not clear the stream bits. It seems to me that in clearing the internal buffer, one would intend that the stream bits would also be reset (in a good state). Is there a reason this is not the defined behavior? Aside from a slight...
3
1391
by: Bob Altman | last post by:
Hi all, Why doesn't the following unmanaged C++ code work as expected: string s; ostringstream strm(s); // This stream should store results in s strm << 25; cout << s << endl; // s still contains an empty string cout << strm.str(); // but the stream internally contains "25"
3
4068
by: Generic Usenet Account | last post by:
With the deprecated ostrstream class, when the constructor is invoked without arguments, memory is dynamically allocated. In that case the onus on freeing the memory lies with the user. Typically this is done by obtaining the char buffer (by invoking the str() method) and then explicitly deleting it. Does the ostringstream class also have the same issue? I mean, if I instantiate ostringstream without any constructor arguments, is the...
2
1488
by: kaferro | last post by:
I use the following code to reset an ID when an order has been filled by more than one trade. For example, order= buy 9 corn, order ID = 101. If the order is filled with three separate trades of, say, 3 each, I need three order IDs (i.e. 101.1, 101.2, 101.3). My simple solution was to use a "char" set to '0' then increment the char for each multiple ID. This works fine if there are only 10 "multi ID trades", but after that the ascii...
11
3634
by: coomberjones | last post by:
I have a few std::strings that I am using to store raw binary data, each of which may very well include null bytes at any point or points. I want to slap them together into a single string, so I tried a std::ostringstream: std::ostringstream oss; oss << x << y << z; std::string result ( oss.str() ); The result shows that feeding the ostringstream with a string just
0
7959
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8263
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6677
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5842
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5421
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3917
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2393
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1492
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.