473,395 Members | 1,464 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,395 software developers and data experts.

string.scanf?

I have a string that looks like:
"123.45:123.45"
I am using sscanf "%f%*c%f" to extract the two floats and ignore the colon.
However there may be more than two floats....
Is there perhaps a better way to do this in C++?
Like make the string appear as a stream and do it with operator>>

string x;
float f1, f2;
x >> f1;
x >> f2;


Jul 22 '05 #1
5 3365
"JustSomeGuy" <no**@nottelling.com> wrote in message
news:WrSvc.664663$Ig.177566@pd7tw2no...
I have a string that looks like:
"123.45:123.45"
I am using sscanf "%f%*c%f" to extract the two floats and ignore the colon. However there may be more than two floats....
Is there perhaps a better way to do this in C++?
Like make the string appear as a stream and do it with operator>>

string x;
float f1, f2;
x >> f1;
x >> f2;


What you are doing is trying to separate tokens that are part of a string.
Lookup the C "strtok" function that will do that for you quite simply. Read
the input in a C-style string and parse it with strtok. Your program can
count the tokens as it goes, you just convert them to float with something
like "atof" or any other way you like.
Jul 22 '05 #2
JustSomeGuy wrote:
I have a string that looks like: "123.45:123.45" I am using sscanf "%f%*c%f"
to extract the two floats and ignore the colon.
However there may be more than two floats....
Is there perhaps a better way to do this in C++?
Like make the string appear as a stream and do it with operator>> cat main.cc #include <iostream>
#include <sstream>
#include <cstdlib>

int main(int argc, char* argv[]) {
std::string x("123.45:123.45");
std::istringstream iss(x);
const
size_t n = 2;
float f[n];
size_t j = 0;
while (iss >> f[j]) {
std::cout << f[j]
<< " = f[" << j << "]" << std::endl;
++j;
char c = '\0';
if (iss >> c && ':' == c)
continue;
else
break;
}
return EXIT_SUCCESS;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main

123.45 = f[0]
123.45 = f[1]
Jul 22 '05 #3
JustSomeGuy wrote:
I have a string that looks like:
"123.45:123.45"
I am using sscanf "%f%*c%f" to extract the two floats and ignore the colon. However there may be more than two floats....
Is there perhaps a better way to do this in C++?
Like make the string appear as a stream and do it with operator>>

string x;
float f1, f2;
x >> f1;
x >> f2;


I recently refactored this ugly code:

typedef std::map<string, string> params_t;

bool
Product(params_t & testCase)
{
double num (strtod(testCase["Input1" ].c_str(), NULL));
double den (strtod(testCase["Input2"].c_str(), NULL));
double quo (strtod(testCase["Product()" ].c_str(), NULL));

return num * den == quo;
}

It now looks like this:

static double
getDouble(params_t & testCase, string columnName)
{
double num(double());
std::stringstream z (testCase[columnName]);
if (z >> num)
return num;
return 0.0; // TODO will throw soon
}

bool
Product(params_t & testCase, string & because)
{
double num (getDouble(testCase, "Input1" ));
double den (getDouble(testCase, "Input2" ));
double quo (getDouble(testCase, "Product()"));

return num * den == quo;
}

Focus on the 'streamstring z' deep inside. One might extract your floats
using:

string x;
stringstream z(x);
double f1, f2;
char space;
z >> f1;
z >> space;
z >> f2;

BTW use 'double' without a reason to use 'float', just as one uses 'int'
without a reason to use 'short' or 'long'. On modern CPUs 'double's can be
faster, too.

My refactor replaced redundant calls to strtod() (another way to do it) with
a single call to operator>>().

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces


Jul 22 '05 #4
Thank you all!
Jul 22 '05 #5
JustSomeGuy wrote:
I have a string that looks like:
"123.45:123.45"


I have two suggestions:

This first one uses a dummy character to use istringstreams capabilities
for parsing...
(You can extend this to more floats by iterating until iss fails....)

using namespace std;
string x("123.45:123.46");

char colon; // Store the colon (or any other character)
float f1, f2; // Our target floating numbers

//Initialize an istringstream
istringstream iss(x);

// Extract the tokens
iss>>f1>>colon>>f2;

The second approach uses the strings find function to figure out the
location of the colons, then send the substring to isstream

string x("123.45:123.46:305.37");
istringstream iss("");
vector<double> mFloats;
string::size_type next_colon;
float temp = 0.0f;

x = std::string("3.0");
do
{
next_colon = x.find(':'); // Find next colon
iss.clear(); // Needed to reuse iss
iss.str(x.substr(0, next_colon)); // Use the first token
x = x.substr(next_colon+1); // Update x (You may want to use a temp
string)
iss>>temp; // Extract the current float
mFloats.push_back(temp); // Add float to the vector
}while(string::npos != next_colon);

// Output the elements
size_t doubles = mFloats.size();
cout<<"Found "<<doubles<<" number..."<<endl;
for(size_t i=0; i<doubles; i++)
{
cout<<"\t"<<i<<": "<<mFloats[i]<<endl;
}
Jul 22 '05 #6

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

Similar topics

5
by: Eduardo Olivarez | last post by:
The following code does not work correctly on my machine. Either one of the scanf()'s alone work perfectly. However, when they are combined, the second scanf() call just reads what the first one...
13
by: Kiran Dalvi | last post by:
Hi, Can anybody please suggest me an efficient approach to find out all possible permutations of a String. e.g. My input string = "ABC". My program should give an output like .... ABC, ACB, BAC,...
7
by: hugo27 | last post by:
obrhy8 June 18, 2004 Most compilers define EOF as -1. I'm just putting my toes in the water with a student's model named Miracle C. The ..h documentation of this compiler does state that when...
24
by: Sathyaish | last post by:
This one question is asked modally in most Microsoft interviews. I started to contemplate various implementations for it. This was what I got. #include <stdio.h> #include <stdlib.h> #include...
5
by: Jonathan Ng | last post by:
Hi, I was wondering if there was a way to include the white spaces in a string. Currently, I am using: scanf("%s", &input); However, this doesn't include the 'space' character or any other...
17
by: Lefty Bigfoot | last post by:
Hello, I am aware that a lot of people are wary of using scanf, because doing it improperly can be dangerous. I have tried to find a good tutorial on all the ins and outs of scanf() but been...
23
by: mrvendetta1 | last post by:
#include <stdio.h> #include <string.h> #include <stdlib.h> #define N 33 void StringToIntArray(const char *s1); void takeinteger(int i); int main() { char string; printf("enter a string of...
7
by: vamshi | last post by:
main() { char str; printf("Enter a string: "); scanf("%",str); printf("%",str); } Can some one help me with this code? when i tried to execute this..... it reads the string untill character
4
by: priyanka | last post by:
Hi, I want to input a string from command line. I use the following program to input the string. #include<stdio.h> int main(){ char input;
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
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...

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.