473,769 Members | 2,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Annoying problem with string::find()

I posted this here one day ago but it seems like it hasn't been put up
for some unknown reason. That gives me a chance to say things a bit
better in this post.

1st of all let's desribe the problem: In ParamGenerate() I want to
find all whitespaces before a certain point in one string. Thus I use
the string::find() function. However it seems like this function
ignores some whitespaces :/ This is really weird and I need your help.

Okay since the function ParamGenerate() itself isn't compilable, I
want to include the least compilable code which I wouldn't say is too
big :) But you gotta understand the purpose of my program so you can
understand better what I'm trying to do in ParamGenerate() . My program
will receive input in the following format:

[ <prefix> ] <COMMAND> <middle param> <middle param> ... <middle
param> <final param>

So the <prefix> is optional (and if inserted is a colon ':') and we
can have MANY <middle param>s (that must not include a colon ':' or a
space ' ') and just one <final param> (which starts with a ':' and can
contain spaces).

I just want to do that kind of seperation to my input with
ParamGenerate() (I remove the leading colon before calling
ParamGenerate() ). However my ParamGenerate() seems to misfunction and
I think that this is caused by the find() function.

<btw> I have also tried implementing the ParamGenerate() function by
going through all the characters in the string and checking if they're
a space but I still have the same problem </btw>

<btw 2> Also in ParamGenerate() if I try to resize the vector to the
result of ParamCount() I get a segfault :/ This is the command I used:

params.resize(P aramCount(s));
</btw 2>

Here's the least compilable code:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

string arg;
vector<string> params(1024);
/*
COMMAND IS LIKE
:user@host <CMD> <PARAMS>

and params are like

<PARAMS> = <MIDDLE PARAMS> <MIDDLE PARAMS> ... <MIDDLE PARAMS> <FINAL
PARAM>

middle params are params that contain no spaces or columns ':'

.... TO BE CONTINUED ...
*/
string RemoveLeadingCo lon(const string &s) {
string s2 = s;
if (s2[0] == ':') s2.erase(0,1);
return s2;
}

int ParamCount(cons t string &s) {
int count=1;
string::size_ty pe i;
for (i=0; i < s.length(); i++) {
if (s[i] == ' ' /*&& !found_column*/ )
count++;
else if (s[i] == ':' /*&& !found_column*/ ) {
return count;
}
}
return count;
}

void ParamGenerate(c onst string &s) {
cout << "initializi ng vars...\n";
string::size_ty pe first_column = s.find(':');
if (first_column == string::npos) first_column=s. length();
string::size_ty pe white_space=0;
string::size_ty pe last=0;
int curr_param=0;
cout << "starting search...\n";
while ((white_space = s.find(' ', white_space+1)) != string::npos &&
white_space <= first_column) {
cout << "found space...\n";
params[curr_param] = s.substr(last,w hite_space);
cout << "substring is \"" << s.substr(last,w hite_space) << "\"\n";
last=white_spac e+1;
curr_param++;
}
params[curr_param] = s.substr(first_ column,s.length ());
}

int main() {

cout << "gimme a cmd:\n";
getline(cin,arg ,'\n');
cout << "you gave me: " << arg << "\n";

cout << "without leading ':' it is: " << RemoveLeadingCo lon(arg) <<
"\n";
ParamGenerate(R emoveLeadingCol on(arg));
cout << "Params generated\n";

int what;
do {
cout << "tell me a num: ";
cin >> what;
if (what <= ParamCount(Remo veLeadingColon( arg)) && what >= 1)
cout << "param[" << what << "] = " << params[what-1] << "\n";
else
cout << "wrong index\n";
} while (what != 0);

return 0;

}
Jul 22 '05 #1
3 2984

"Chris Mantoulidis" <cm****@yahoo.c om> wrote in message
news:a8******** *************** ***@posting.goo gle.com...
I posted this here one day ago but it seems like it hasn't been put up
for some unknown reason. That gives me a chance to say things a bit
better in this post.


I haven't delved a lot into your code.
I think perhaps this is an easier way to parse an input string.

#include<iostre am>
#include<string >
#include<vector >
#include <sstream>
using namespace std;

template <class T>
vector<T> StringToVector( string& Str )
{
istringstream iss( Str );
return vector<T>( istream_iterato r<T>(iss),istre am_iterator<T>( ) );
}

int main(){
string str = " Here is a command ";
vector<string> vec(StringToVec tor<string>(str ));
vector<string>: :const_iterator itr;
for(itr = vec.begin(); itr!= vec.end (); ++itr)
cout << *itr; // Print Hereisacommand
}

Best wishes,
Sharad
Jul 22 '05 #2

"Chris Mantoulidis" <cm****@yahoo.c om> wrote in message
news:a8******** *************** ***@posting.goo gle.com...
I posted this here one day ago but it seems like it hasn't been put up
for some unknown reason. That gives me a chance to say things a bit
better in this post.

cout << "found space...\n";
params[curr_param] = s.substr(last,w hite_space);
cout << "substring is \"" << s.substr(last,w hite_space) << "\"\n";


You'll have better results with

params[curr_param] = s.substr(last,w hite_space - last);
cout << "substring is \"" << s.substr(last,w hite_space - last) << "\"\n";

but I wouldn't swear that your code doesn't have other bugs in it.

john
Jul 22 '05 #3
"John Harrison" <jo************ *@hotmail.com> wrote in message news:<c1******* ******@ID-196037.news.uni-berlin.de>...
"Chris Mantoulidis" <cm****@yahoo.c om> wrote in message
news:a8******** *************** ***@posting.goo gle.com...
I posted this here one day ago but it seems like it hasn't been put up
for some unknown reason. That gives me a chance to say things a bit
better in this post.

cout << "found space...\n";
params[curr_param] = s.substr(last,w hite_space);
cout << "substring is \"" << s.substr(last,w hite_space) << "\"\n";


You'll have better results with

params[curr_param] = s.substr(last,w hite_space - last);
cout << "substring is \"" << s.substr(last,w hite_space - last) << "\"\n";

but I wouldn't swear that your code doesn't have other bugs in it.

john


Oh so 2nd param in substr() is the length and not where the stop mark
is? Feh what a silly bug :/

I'll check out if I got more errors in my program in a min :)
Jul 22 '05 #4

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

Similar topics

3
33869
by: hokiegal99 | last post by:
How do I say: x = string.find(files, 'this', 'that', 'the-other') currently I have to write it like this to make it work: x = string.find(files, 'this') y = string.find(files, 'that') z = string.find(files, 'the-other')
10
33679
by: hokieghal99 | last post by:
import os, string print " " setpath = raw_input("Enter the path: ") def find_replace(setpath): for root, dirs, files in os.walk(setpath): fname = files for fname in files: find = string.find(file(os.path.join(root,fname), 'rb').read(), 'THIS') print find
5
1842
by: MyHaz | last post by:
OK i find this a quark in string.find that i think needs some consideration. Normally if a substring is not in the searched_string then string.find returns -1 (why not len(searched_string) + 1, i don't know but nevermind that) but what if a searched_string == '' ? Then string.find(substring,searched_string) == 0 ? example:
108
6454
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
0
1068
by: Ian Lazarus | last post by:
Hello, A call to std::basic_string<wchar_t>::find(...) from within a class library is not working as expected. The value passed to find is 0x61, but the value it receives is 0xE961. What's happening? How do I fix this? Thanks // stack trace msvcp71d.dll!std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >::find(_Ch='?' (0xE961), _Off=0x00000000) mscorwks.dll!791befaf()
2
1761
by: Gaijinco | last post by:
I was trying a function that read an string (which previously had attached two special characters & for the beginning of the word and # for the end of the word) and if it was "<word>ize" it changed into "change into <word>". I did this function: bool Ize(string& s) { bool is=false; string eval="ize"; int end=s.find('#');
5
4615
by: PaulH | last post by:
I have a function that is stripping off some XML from a configuration file. But, when I do a search for the pieces I want to strip, the std::string::find() function always returns std::string::npos (-1). I can print out the config string at the beginning of CleanCfgFile(), and the strings are there exactly the way I'm looking for them. So, the question is, what am I doing wrong? Function() {
11
3705
by: Ko van der Sloot | last post by:
Hello I was wondering which behaviour might be expected (or is required) for the following small program. I would expect that find( "a", string::npos ) would return string::npos but is seems to be dependant on which string is searched for. On my system, using gcc 4.1.2, I get: pos1=2 problem because pos1=0
2
2176
by: Soneji | last post by:
Just a quickie today... Is there another ( better ) way to get the second value from this string::find example: std::string str( "More strings of the string variety" ); size_t loc; loc = str.find( "string" ); loc = str.find( "string", loc + 1, 6 );
0
9423
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
10210
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
10043
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
9990
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
8869
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
7406
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...
1
3956
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
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
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.