473,387 Members | 3,684 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Tokenizing strings to long integers and doubles

424 256MB
Hello,

I need to get the following string

"12332321213,SomeText,3.141592654"

into constituent variables: an unsigned long int, a string and a double. So far I have,
Expand|Select|Wrap|Line Numbers
  1. string line = "12332321213,SomeText,3.141592654";
  2. unsigned long int id; // should become 12332321213
  3. string name; // should become "SomeText"
  4. double number; // should become 3.141592654
  5.  
  6. vector <string> lineTokens;
  7. istringstream iss(line) // Create string stream
  8.  
  9. string token;
  10. while (getline(iss,token,',')) {
  11.    lineTokens.push_back(token);
  12. }
  13.  
Now I have a vector of strings. So the question arises: how do I convert the string "12332321213" to a long int and "3.141592654" to a double? Of course, atoi() comes to mind but it looks like it only converts to single precision integers.

I tried static_cast<unsigned long int>() but I get the compile-time error " invalid static_cast from type `std::string' to type `long unsigned int' ".

(An irrelevant aside: how do I specify what kind of code I'm posting in this forum because mine comes up as 'text' and not 'cpp'?)
Sep 4 '07 #1
8 2748
arnaudk
424 256MB
D'oh! Got it: strtoul(); and strtod();
[blush]
Sep 4 '07 #2
Ganon11
3,652 Expert 2GB
As an answer to your [code] tag related question, there is an option to include a "=<code type here>" between the word CODE and the closing bracket. For instance, the following [code] segment uses =cpp:

Expand|Select|Wrap|Line Numbers
  1. cout << "Now you know this is C++ code!" << endl;
  2.  
There's also =java, =c, =php, etc. etc.
Sep 4 '07 #3
JosAH
11,448 Expert 8TB
D'oh! Got it: strtoul(); and strtod();
[blush]
You forgot the [/blush] tag, or are you still blushing ;-)

kind regards,

Jos
Sep 4 '07 #4
weaknessforcats
9,208 Expert Mod 8TB
D'oh! Got it: strtoul(); and strtod();
[blush]
Yes. Providing you write in C. But this is C++.

You have:

An int. A comma. A string. A comma, A double.

string line = "12332321213,SomeText,3.141592654";
So, use a stringstream:

Expand|Select|Wrap|Line Numbers
  1. stringstream ss;
  2. ss << line;
  3. int AnInt;
  4. char AChar;
  5. string AString;
  6. double ADouble;
  7. ss >> AnInt >>AChar >>AString>>AChar>>ADouble;
  8.  
and you are done.

And stop using relic C functions from the old C string library. C++ strings are no C-style strings.
Sep 5 '07 #5
arnaudk
424 256MB

You have:

An int. A comma. A string. A comma, A double.

So, use a stringstream:

Expand|Select|Wrap|Line Numbers
  1. stringstream ss;
  2. ss << line;
  3. int AnInt;
  4. char AChar;
  5. string AString;
  6. double ADouble;
  7. ss >> AnInt >>AChar >>AString>>AChar>>ADouble;
  8.  
Thanks, I'd to bury my torturous C past. But in your code, how does ss know that the delimiter is a comma? Is that default behavior? What if my delimiter were something else?
Sep 6 '07 #6
Ganon11
3,652 Expert 2GB
I think that the ss detects what kind of variable it is being asked for and spits out what is necessary. It is first asked for an integer, and so it returns the integer it has in front. Then it is asked for a single char. Well, the next char is the comma, so it spits that out.

There might be trouble, though, asking it for a string and then a char, because a comma could be part of a string.
Sep 6 '07 #7
arnaudk
424 256MB
Apparently, for numeric values, the >> operator

"Extracts characters from the input sequence and tries to interpret them as a numeric value of the given parameter's type. If successful the value is stored in val. The specific way in which the data is parsed depends on the manipulators previously used on the stream and on its associated locale."

For strings, however, it

"Extracts characters and stores them as a c-string (i.e. in succesive locations starting at location pointed by str and terminated by a null-character). Extraction ends when the next character is either a valid whitespace or a null character, or if the End-Of-File is reached.The terminating null character is automatically appended after the extracted characters.
The extraction operation can be limited to a certain number of characters (thus avoiding the possibility of buffer overflow) if the field width (which can be set with ios_base::width or setw) is set to a value greater than zero. In this case, the extraction ends one character before the count of characters extracted reaches the value of field width, leaving space for the ending null character. After a call to this extraction operation the value of the field width is automatically reset to zero."

(from cplusplus.com)

[/blush]
Sep 6 '07 #8
weaknessforcats
9,208 Expert Mod 8TB
Thanks, I'd to bury my torturous C past. But in your code, how does ss know that the delimiter is a comma? Is that default behavior? What if my delimiter were something else?
It's not ss.

It's the operator>> function, which may or may not be part of the stringstgream class.

Each operator>> overload has two operators. The first operator is the input stream and the second operator is the variable to the right of the >> operator.

So, >> aChar assumes there is a char as the next byte in the inout stream. If you don't know that, then you can't use the >> operator at all.

>> operations are all formatted operations since they presuppose you know the format of the data in the inout stream.
Sep 7 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

50
by: dataangel | last post by:
I wrote a function to compare whether two strings are "similar" because I'm using python to make a small text adventure engine and I want to it to be responsive to slight mispellings, like...
28
by: David Rubin | last post by:
I looked on google for an answer, but I didn't find anything short of using boost which sufficiently answers my question: what is a good way of doing string tokenization (note: I cannot use boost)....
12
by: jose luis fernandez diaz | last post by:
Hi, My OS is: cronos:jdiaz:tmp>uname -a HP-UX cronos B.11.11 U 9000/800 820960681 unlimited-user license I compile in 64-bits mode the program below:
16
by: agay | last post by:
Hi, I would like to get feedback on a "switching on strings" utility: http://shum.huji.ac.il/~agay/sos Thanks a. agay
18
by: a | last post by:
short s; long l; s= -2; l= -3; printf("% _ %_",s, l); What characters should be filled out in the formatted string for output? Thanx
10
by: Bryan Parkoff | last post by:
The guideline says to use %f in printf() function using the keyword float and double. For example float a = 1.2345; double b = 5.166666667; printf("%.2f\n %f\n", a, b);
67
by: lcw1964 | last post by:
This may be in the category of bush-league rudimentary, but I am quite perplexed on this and diligent Googling has not provided me with a clear straight answer--perhaps I don't know how to ask the...
3
by: Jeff | last post by:
....still new to vb.net 2005 I understand the concept of arrays, and have used them in other languages, but was hoping that someone could get me started with something. I have a fairly long...
2
by: merrittr | last post by:
Hi all, i am struggling with c strings still here is what i want, pass in 2 string vals convert them to doubles add them then convert the result back to a char string and return it to a printf...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.