473,770 Members | 3,710 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++: Help output nested strings

Could you please explain me how can I output nested strings?

Here is an example:

"adsd{rf[dfF]km}xcv"

The output should start from the inner parentheses, such as:

dfF
rfkm
adsdxcv
Thanks!

Feb 20 '06 #1
9 2205
Diane wrote:
Could you please explain me how can I output nested strings?

Here is an example:

"adsd{rf[dfF]km}xcv"

The output should start from the inner parentheses, such as:

dfF
rfkm
adsdxcv


This isn't a C++ problem. You need to build those strings.
It's a programming problem. What you have is a stack of
strings represented in a certain grammatical form. What you
need to do is to convert one representation into the other
and then output the other (the stack of strings). How to
convert one into the other is not a _language_ problem. You
are supposed to come up with an algorithm.

Come back once you have the algorithm and we'll help you put
it into C++ terms. Of course, if you have any C++ experience
at all, try writing your program and then we can help you get
it to work.

Also, as I see it, the string building function should probably
be recursive. It should start building its string either at the
beginning or right after getting an opening bracket/brace/paren
and end with the matching closing bracket/brace/paren or at the
end of the input. Once the function built the string it can
simply output it.

V
--
Please remove capital As from my address when replying by mail
Feb 20 '06 #2
Thanks for your reply Victor!

Here is what I tried to do, but it doesn't seem to work properly.
Any suggestions?

int main()
{
Stack s;
char symbol;
int counter = -1;
char match;

// read all characters from keyboard and push them in the stack
while((symbol=c in.get()) != '\n')
{
s.push(symbol);
counter++;
}
//scan the stack to output the nested strings
for(int i=0; i<counter; i++)
{

if(symbol == '{' || symbol == '(' || symbol == '[')
{
cout << "\n";
match = symbol;
}

if(symbol == '}' || symbol == ')' || symbol == ']')
{
if( (symbol == '}' && match == '{') || (symbol == ')' &&
match == '(')
|| (symbol == ']' && match == '[') )
{
s.pop();
}
}

}

return 0;

}

Feb 21 '06 #3
Diane wrote:
Here is what I tried to do, but it doesn't seem to work properly.
Any suggestions?
You need to fix it.

[...]
if(symbol == '{' || symbol == '(' || symbol == '[')
{
cout << "\n";
Wouldn't it make more sense to do all output at the _closing_
character?
match = symbol;
}

if(symbol == '}' || symbol == ')' || symbol == ']')
{
if( (symbol == '}' && match == '{') || (symbol == ')' &&
match == '(')
|| (symbol == ']' && match == '[') )
{
s.pop();
... and you're losing the string here instead of outputting it...
}
}

V
--
Please remove capital As from my address when replying by mail
Feb 21 '06 #4
In article <11************ *********@f14g2 000cwb.googlegr oups.com>,
"Diane" <fr*********@ho tmail.com> wrote:
Could you please explain me how can I output nested strings?

Here is an example:

"adsd{rf[dfF]km}xcv"

The output should start from the inner parentheses, such as:

dfF
rfkm
adsdxcv


Paste the code below in your program (replace what you have) and play
with the code in the "parse_stri ng" function until it works. Instead of
sending output to "cout" send it to "os".

void parse_string( const string& s, ostream& os ) {
// change the code in this method
os << s;
}

int main() {
string test( "hello" );
stringstream ss;
parse_string( test, ss );
assert( ss.str() == test );

test = "Good[hello]by";
ss.str( "" );
parse_string( test, ss );
assert( ss.str() == "hello\nGoo dby" );

test = "Good(hello)by" ;
ss.str( "" );
parse_string( test, ss );
assert( ss.str() == "hello\nGoo dby" );

cout << "working\n" ;
}

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 21 '06 #5
Daniel T. wrote:
In article <11************ *********@f14g2 000cwb.googlegr oups.com>,
"Diane" <fr*********@ho tmail.com> wrote:

Could you please explain me how can I output nested strings?

Here is an example:

"adsd{rf[dfF]km}xcv"

The output should start from the inner parentheses, such as:

dfF
rfkm
adsdxcv

Paste the code below in your program (replace what you have) and play
with the code in the "parse_stri ng" function until it works. Instead of
sending output to "cout" send it to "os".

void parse_string( const string& s, ostream& os ) {
// change the code in this method


I recommend the boost::spirit framework to create a simple parser. Question
for the OP: do you want to output strings such as
"abc{xyz}ijk{AB C[lmn]dkd[123]}uiop{[sdf]}"? First you must define a set of
rules the matched strings must adhere to (number of nestings allowed, etc.)
before you can do anything.
os << s;
}


<snip>

--
To reply, take of all ZIGs !!
Feb 21 '06 #6
What does the parse_string method suppose to do?

I think that the stringstream works only with whitespaces. What if I
have other delimiters?

Feb 21 '06 #7
In article <11************ **********@g44g 2000cwa.googleg roups.com>,
"Diane" <fr*********@ho tmail.com> wrote:
What does the parse_string method suppose to do?
In the long term, it's supposed to output nested strings like your
example. For now, it's supposed to make the tests in main pass.

Notice that the last line in 'main' is [cout << "working\n" ;] Your job
is to put code in "parse_stri ng" until the program outputs "working"
Once you have done that, you will be one step closer to having your
assignment done.
I think that the stringstream works only with whitespaces. What if I
have other delimiters?


For your purposes, stringstream works exactly like cout, except it
outputs to a string rather than the screen.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 21 '06 #8
Thanks!

Feb 21 '06 #9
In article <11************ **********@g47g 2000cwa.googleg roups.com>,
"Diane" <fr*********@ho tmail.com> wrote:
Thanks!


Check your "fr*********@ho tmail.com" account email...

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 21 '06 #10

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

Similar topics

8
2954
by: Marko Faldix | last post by:
Hello, with Python 2.3 I can write umlauts (a,o,u umlaut) to a file with this piece of code: import codecs f = codecs.open("klotentest.txt", "w", "latin-1") print >>f, unicode("My umlauts are ä, ö, ü", "latin-1")
9
2161
by: OKB (not okblacke) | last post by:
For a variety of reasons, I'm interested in putting together some code that will allow me to created structures out of nested classes, something like: class class1: def methA(self): print "Some code here" class class2: propA = "A" def methB(self):
3
6472
by: Tcs | last post by:
My backend is DB2 on our AS/400. While I do HAVE DB2 PE for my PC, I haven't loaded it yet. I'm still using MS Access. And no, I don't believe this is an Access question. (But who knows? I COULD be wrong... :) I've tried the access group...twice...and all I get is "Access doesn't like ".", which I know, or that my query names are too long, as there's a limit to the length of the SQL statement(s). But this works when I don't try to...
6
559
by: B0nj | last post by:
I've got a class in which I want to implement a property that operates like an indexer, for the various colors associated with the class. For instance, I want to be able to do 'set' operations like MyClass.MyColors = Color.Green or, a 'get', such as Color forecolor = MyClass.MyColors; I want to use an indexer so I can take parameters, such as the color type (e.g. "Foreground", "Background" etc.). With a single member function I couldn't...
4
15077
by: Kevin Mansel via .NET 247 | last post by:
Ok, basically this is my problem. I'm building a console app tocall a dos program. So i'm using the Shell command to call theprogram, now depending on what happens, I want to read theoutput that this program returns. I'm just missing the stepshere. I know that I can set the Shell command to an integer,but this only returns a 0 to me telling me that it executed, notwhat is being returned to the console by that application. Isthere a way to...
9
7365
by: a | last post by:
I need to write a regular expression to match a quoted string in which the double quote character itself is represented by 2 double quotes. For example: "beginning ""nested quoted string"" end" Any idea how to write this in boost::xpressive or boost::regex. Thanks,
1
2435
by: Henrik Bechmann | last post by:
All, I'm trying to spoof Google's vertical tabs in a vertical menu structured with nested UL/LI elements. To do this, I need to find out where the anchor in the LI is, and then create an absolute positioned div to bridge the space between the menu and the content page. This works with one level of LI's. However, with more than one, the
8
5942
by: Sheldon | last post by:
Hi, Can anyone help with this problem with setting up nested structures and initializing them for use. I have created several structs and placed them in a super struct that I will then pass to some functions. I have defined them in the following manner: typedef struct trans Transient; typedef struct sats Satellites;
0
2779
by: LanaR | last post by:
Hello, one sql statement is causing severe performance issue. The problem occurs only in UDB environment, the same statemnt on the mainframe is running fine. I have an explain output from the sql. The statement itself is not that complicated, it is 3 selects and union all. Explain output is pretty big, but I could not find anything unusual. I'm new to db2 and I could be missing stuff. I am posting the explain output below and I really...
0
9595
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
9432
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10059
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10008
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8891
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...
0
5313
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3974
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
3
2822
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.