473,846 Members | 1,905 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unable to correctly concatenate a string variable

I have been to recreate a problem that I am having with strings with
the trivial code snippet given below. In the trivial code example, I
am reading five lines from a data file, each line having only one word.
I try to concatenate each word read into a string variable, separated
by a delimiter character. Even though I am able to read the words from
the file correctly, I am not able to correctly concatenate the string.
I was expecting the output to be a concatenated string containing all
the words, separated by the delimiter character, but that is not what
is happening.

I know that I am doing something silly. Any help will be appreciated.

Song

Code snipped follows

////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

#define WORD_SEPARATOR ":"
#define DATAFILE "./data.dat"

//////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
bool
readRandomLine( const string fileName, string& line)
{
bool ret = false;

ifstream ifs(fileName.c_ str());
if(!ifs)
{
cerr << "Cannot open file " << fileName << " ....ignoring" << endl;
return ret;
}

string token;
unsigned long nlCount = 0;
while(getline(i fs, token))
nlCount++;

if(nlCount)
{
ifs.clear();
ifs.seekg(0);

int randLineNum = rand()%nlCount + 1;

for(unsigned long i = 1; (i <= randLineNum) && getline(ifs, token);
i++);

if(ifs)
{
line = token;
ret = true;
}
}

ifs.close();
return ret;
}
//////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
bool
getWord(string& word, string fileName)
{
bool status = true;

status = readRandomLine( fileName, word);
return status;
}

//////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
void
fillString(stri ng& val)
{
for(int i = 0; i < 5; i++)
{
string nextWord;
if(!getWord(nex tWord, DATAFILE))
break;
else
{
cout << "Fetched word " << nextWord << endl;
val += nextWord;
val += WORD_SEPARATOR;
}
}

cout << endl;
}
//////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
main()
{
srand(time(NULL ));
rand();

string valStr;
fillString(valS tr);

cout << "The value string is: " << endl
<< valStr << endl;

return 0;
}

/////////////////////// Data File "./data.dat" ///////////////////
oak
object
objection
objective
obligation
observation
observer
obstacle
occasion
occupation
occurrence
ocean
Octavia
Octavio
odds
of

Sep 1 '06 #1
5 2813
Generic Usenet Account wrote:
I have been to recreate a problem that I am having with strings with
the trivial code snippet given below. In the trivial code example, I
am reading five lines from a data file, each line having only one
word. I try to concatenate each word read into a string variable,
separated by a delimiter character. Even though I am able to read
the words from the file correctly, I am not able to correctly
concatenate the string. I was expecting the output to be a
concatenated string containing all the words, separated by the
delimiter character, but that is not what is happening.
What *is* happening?
[...]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 1 '06 #2
Generic Usenet Account wrote:
I know that I am doing something silly. Any help will be appreciated.
Compiles and runs fine for me. What are you experiencing?

Jens
Sep 2 '06 #3
Hi,

I think you should have linked your data file in your message instead of
including it.

Are you using a windows file on an linux/unix system perhaps? Then there
will be a carriage return at the end of each word (i.e. if you output it
normaly only the last word will show completely with parts of previous words
after it.

Give more info or the format of your input file.

--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

"Generic Usenet Account" <us****@sta.sam sung.comwrote in message
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
>I have been to recreate a problem that I am having with strings with
the trivial code snippet given below. In the trivial code example, I
am reading five lines from a data file, each line having only one word.
I try to concatenate each word read into a string variable, separated
by a delimiter character. Even though I am able to read the words from
the file correctly, I am not able to correctly concatenate the string.
I was expecting the output to be a concatenated string containing all
the words, separated by the delimiter character, but that is not what
is happening.

I know that I am doing something silly. Any help will be appreciated.

Song

Code snipped follows

////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

#define WORD_SEPARATOR ":"
#define DATAFILE "./data.dat"

//////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
bool
readRandomLine( const string fileName, string& line)
{
bool ret = false;

ifstream ifs(fileName.c_ str());
if(!ifs)
{
cerr << "Cannot open file " << fileName << " ....ignoring" << endl;
return ret;
}

string token;
unsigned long nlCount = 0;
while(getline(i fs, token))
nlCount++;

if(nlCount)
{
ifs.clear();
ifs.seekg(0);

int randLineNum = rand()%nlCount + 1;

for(unsigned long i = 1; (i <= randLineNum) && getline(ifs, token);
i++);

if(ifs)
{
line = token;
ret = true;
}
}

ifs.close();
return ret;
}
//////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
bool
getWord(string& word, string fileName)
{
bool status = true;

status = readRandomLine( fileName, word);
return status;
}

//////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
void
fillString(stri ng& val)
{
for(int i = 0; i < 5; i++)
{
string nextWord;
if(!getWord(nex tWord, DATAFILE))
break;
else
{
cout << "Fetched word " << nextWord << endl;
val += nextWord;
val += WORD_SEPARATOR;
}
}

cout << endl;
}
//////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
main()
{
srand(time(NULL ));
rand();

string valStr;
fillString(valS tr);

cout << "The value string is: " << endl
<< valStr << endl;

return 0;
}

/////////////////////// Data File "./data.dat" ///////////////////
oak
object
objection
objective
obligation
observation
observer
obstacle
occasion
occupation
occurrence
ocean
Octavia
Octavio
odds
of

Sep 2 '06 #4
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~
Jens Theisen wrote:
Generic Usenet Account wrote:
I know that I am doing something silly. Any help will be appreciated.

Compiles and runs fine for me. What are you experiencing?

Jens
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~
Victor Bazarov wrote:
What *is* happening?
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~
Moonlit wrote:
Hi,

I think you should have linked your data file in your message instead of
including it.

Are you using a windows file on an linux/unix system perhaps? Then there
will be a carriage return at the end of each word (i.e. if you output it
normaly only the last word will show completely with parts of previous words
after it.

Give more info or the format of your input file.

--
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~

For your benefit, I am providing the expected output and the actual
output. Kindly realize that what you get may be slightly different
from what I got since I am reading five lines (each having one word)
randomly from the file.

Thanks,
Song
Expected output:
=============== =
Fetched word obligation
Fetched word occasion
Fetched word occurrence
Fetched word ocean
Fetched word Octavio

The value string is:
obligation:occa sion:occurrence :ocean:Octavio

Actual output:
==============
Fetched word obligation
Fetched word occasion
Fetched word occurrence
Fetched word ocean
Fetched word Octavio

The value string is:
:Octavionce

Sep 2 '06 #5
Hi,

Ok, that is exactly what I said. The last part of occurence and the first
part Octavio. The whole string is there but because the carriage return
jumps back to the beginning of the line you only see part of the words and
the last word completely

occurrence
Octavio
solution. After reading Line from your file remove the carriage return:

#include <algorithm>

Line.erase( remove_if( Line.begin(), Line.end(), bind2nd( equal_to<char>( ),
'\r' ) ), Line.end() );
--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

<us****@sta.sam sung.comwrote in message
news:11******** *************@7 4g2000cwt.googl egroups.com...
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~
Jens Theisen wrote:
>Generic Usenet Account wrote:
I know that I am doing something silly. Any help will be appreciated.

Compiles and runs fine for me. What are you experiencing?

Jens

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~
Victor Bazarov wrote:
>What *is* happening?

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~
Moonlit wrote:
>Hi,

I think you should have linked your data file in your message instead of
including it.

Are you using a windows file on an linux/unix system perhaps? Then there
will be a carriage return at the end of each word (i.e. if you output it
normaly only the last word will show completely with parts of previous
words
after it.

Give more info or the format of your input file.

--

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~

For your benefit, I am providing the expected output and the actual
output. Kindly realize that what you get may be slightly different
from what I got since I am reading five lines (each having one word)
randomly from the file.

Thanks,
Song
Expected output:
=============== =
Fetched word obligation
Fetched word occasion
Fetched word occurrence
Fetched word ocean
Fetched word Octavio

The value string is:
obligation:occa sion:occurrence :ocean:Octavio

Actual output:
==============
Fetched word obligation
Fetched word occasion
Fetched word occurrence
Fetched word ocean
Fetched word Octavio

The value string is:
:Octavionce

Sep 2 '06 #6

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

Similar topics

2
2424
by: Len Burman | last post by:
I have some code in a form which inputs a friends email address and when you submit it sends the message to the person at the address. I want to be able to email to the variable name and also a hard coded address. When I actually input two addresses, it sends to both. The partial code reads: Set objMail = CreateObject("CDONTS.NewMail") objMail.From= request.form("youremail") 'Specify sender's address...
10
1903
by: Jack | last post by:
Hi, I cannot get the date format correctly in dynamic sql statement, after trying various ways of handling it. I need some help with the date format in the following dynamic sql statement. Any help is appreciated in advance. While running the asp page, I still get an error as Error Type: Microsoft VBScript runtime (0x800A000D) Type mismatch: 'Format' DYNAMIC SQL STATEMENT:
5
5891
by: Henrik | last post by:
The problem is (using MS Access 2003) I am unable to retrieve long strings (255 chars) from calculated fields through a recordset. The data takes the trip in three phases: 1. A custom public function returns a long string. This works. 2. A query has a calculated field based on the custom function above. This works when the query is run directly.
3
9556
by: nandan | last post by:
Yes. My client has a proxy server. That much i know. In my application I make two kinds of calls that are affected by the proxy server I finally got the webservice call working. But my httpwebrequest.GetReponse() function call throws the above error. So here's what i do in the case it works.. //THIS WORKS
13
21866
by: sinbad | last post by:
hi, how to concatenate a "hash defined" constant value to another "hash defined" constant string. For example #define ABC 100 #define MYSTR "The value of ABC is" Now i need a string that will concatenate the value of ABC to MYSTR . I need this at compile time.
10
7467
by: Aaron Hoffman | last post by:
Hello, I'm hoping someone might be able to offer some guidance to my problem. I have one query in MS Access which consists of 2 tables joined by a SEQUENCE_ID. By joining the two tables I am able to produce a query that gives me two fields, Part_Number and Product_Type. Below you can see some sample data: Part_Number Product_Type 10MC35231 XYZ1A
1
3384
by: Tony Bansten | last post by:
Assume I want to concatenate a literal text value and a variable value for a function parameter then the following does NOT work: objWorkbook.SaveAs("D:\work\v1_" + Filename) The variable "Filename" is filled with a valid value. So how do I otherwise concatenate two parts? Tony
3
1110
by: sgmbuk | last post by:
I have no clue why this is happening. The intended behaviour is: 1. Passing strings of numbers using the numbered buttons (1..0). 2. Concatenate the strings above into one and converting it into an integer. 3. Select an operation ( +, -, * and /) 4. Passing strings of numbers using the numbered buttons (1..0). 5. Concatenate the strings above into one and converting it into an integer. 6. Perform the calculation and output the...
53
8440
by: souporpower | last post by:
Hello All I am trying to activate a link using Jquery. Here is my code; <html> <head> <script type="text/javascript" src="../../resources/js/ jquery-1.2.6.js"</script> <script language="javascript" type="text/javascript">
0
9727
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
10978
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
10643
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
10705
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,...
1
7879
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
7050
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
5907
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4521
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
3158
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.