473,748 Members | 8,392 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

extracting integers from a string.

dor
i have an input file named input.txt where all the data looks like
this:
(4,10) 20
(5,3) 13
(7,19) 6
..
..
..

the numbers are random. i need to use every number in each line
individually as an integer. i know how to use ifstream to get every
line into a string variable, but i dont know how to manipulate it to
get three different int variables out of that one string variable.
so my string is string line = "(4,10) 20";
what do i do?
can somebody help me please?

Mar 13 '06 #1
4 2570

dor wrote:
i have an input file named input.txt where all the data looks like
this:
(4,10) 20
(5,3) 13
(7,19) 6
.
.
.

the numbers are random. i need to use every number in each line
individually as an integer.
I doubt it. I guess you really should have a class that contains
exactly three
integers, and create one instance of that class per line. Let's call it
class X;
i know how to use ifstream to get every
line into a string variable, but i dont know how to manipulate it to
get three different int variables out of that one string variable.
so my string is string line = "(4,10) 20";


What would you do if you'd have a std::istream& operator<<
(std::istream&, X) ?

HTH,
Michiel Salters

Mar 13 '06 #2
"dor" <ke*****@gmail. com> wrote in message
news:11******** **************@ i39g2000cwa.goo glegroups.com.. .
i have an input file named input.txt where all the data looks like
this:
(4,10) 20
(5,3) 13
(7,19) 6
.
.
.

the numbers are random. i need to use every number in each line
individually as an integer. i know how to use ifstream to get every
line into a string variable, but i dont know how to manipulate it to
get three different int variables out of that one string variable.
so my string is string line = "(4,10) 20";
what do i do?
can somebody help me please?


look at std::string's find_first_of and related functions.

I.E. this outputs "4":

std::string MyString = "(4,10) 20";
std::cout << MyString.substr (1, MyString.find_f irst_of(",") - 1);

then if you took the substr of the find_first_of + 1 until the first ) - 1
you would get the 10.

etc..

To convert them to numbers you have your choice of ways. My favorite way is
like this:

#include <sstream>
template<typena me T, typename F > T StrmConvert( F from )
{
std::stringstre am temp;
temp << from;
T to = T();
temp >> to;
return to;
}

Used like this:
RefreshRate = StrmConvert<int >( Refresh );
where Refresh is a std::string

this StrmConvert is quite useful and can convert int/float/std::string
etc... to/from each other.

This is not the only way, but is the way I would do it. If you have any
more question ask.
Mar 14 '06 #3
In article <11************ **********@i39g 2000cwa.googleg roups.com>,
"dor" <ke*****@gmail. com> wrote:
i have an input file named input.txt where all the data looks like
this:
(4,10) 20
(5,3) 13
(7,19) 6
.
.
.

the numbers are random. i need to use every number in each line
individually as an integer. i know how to use ifstream to get every
line into a string variable, but i dont know how to manipulate it to
get three different int variables out of that one string variable.
so my string is string line = "(4,10) 20";
what do i do?
can somebody help me please?


istream& read( istream& in, int& a, int& b, int& c ) {
int ta, tb, tc;
char ch;
if ( ! ( in >> ch && ch == '(' &&
in >> ta >> ch && ch == ',' &&
in >> tb >> ch && ch == ')' &&
in >> tc ) )
in.clear( ios_base::badbi t );
else {
a = ta;
b = tb;
c = tc;
}
return in;
}

--
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.
Mar 14 '06 #4
In article <2R************ **@fe04.lga>,
"Jim Langston" <ta*******@rock etmail.com> wrote:
"dor" <ke*****@gmail. com> wrote in message
news:11******** **************@ i39g2000cwa.goo glegroups.com.. .
i have an input file named input.txt where all the data looks like
this:
(4,10) 20
(5,3) 13
(7,19) 6
.
.
.

the numbers are random. i need to use every number in each line
individually as an integer. i know how to use ifstream to get every
line into a string variable, but i dont know how to manipulate it to
get three different int variables out of that one string variable.
so my string is string line = "(4,10) 20";
what do i do?
can somebody help me please?


look at std::string's find_first_of and related functions.

I.E. this outputs "4":

std::string MyString = "(4,10) 20";
std::cout << MyString.substr (1, MyString.find_f irst_of(",") - 1);

then if you took the substr of the find_first_of + 1 until the first ) - 1
you would get the 10.

etc..

To convert them to numbers you have your choice of ways. My favorite way is
like this:

#include <sstream>
template<typena me T, typename F > T StrmConvert( F from )
{
std::stringstre am temp;
temp << from;
T to = T();
temp >> to;
return to;
}

Used like this:
RefreshRate = StrmConvert<int >( Refresh );
where Refresh is a std::string

this StrmConvert is quite useful and can convert int/float/std::string
etc... to/from each other.

This is not the only way, but is the way I would do it. If you have any
more question ask.


That is certainly one way to do it. (I came up with about 5 different
ways before posting, including the above.) I didn't like the idea of
reading from the stream, then putting parts of the data back into a
stream just to read it out again.

That said, one method I cam up with was:

bool not_digit( char c ) {
return ! isdigit( c );
}

istream& read( istream& in, int& a, int& b, int& c ) {
string str;
getline( in, str );
replace_if( str.begin(), str.end(), &not_digit, ' ' );
stringstream ss( str );
ss >> a >> b >> c;
return in;
}

But the above doesn't check the format of the input file.

and of course there is the C-ish way:

istream& read( istream& in, int& a, int& b, int& c ) {
string str;
getline( in, str );
if ( sscanf( str.c_str(), "(%d,%d) %d", &a, &b, &c ) != 3 )
in.clear( ios_base::badbi t );
return in;
}

But there's some duplication in the above I don't like.
--
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.
Mar 14 '06 #5

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

Similar topics

3
2890
by: Mike Vallely | last post by:
If anyone could help me with my problem I'd greatly appreciate it, this question probably has a quick easy answer but I've been wanting to punch the wall for the last hour because of it. I have a string IDNUM = "12345"; I need to do simple arithmetic with the integers in this string. The way I've been trying and failing is by doing something similar to this:
1
1535
by: andy.lee23 | last post by:
Hi, I've been learning C for a couple of weeks and I need some help. I have a text file and I want to extract integers from it to perform calculations. The format of the file is as follows: 3 2 3 5 5 7
2
2814
by: Dickyb | last post by:
Extracting an Icon and Placing It On The Desktop (C# Language) I constructed a suite of programs in C++ several years ago that handle my financial portfolio, and now I have converted them to C#. The only significant problem that I have encountered in the conversion is this one - extracting an icon from the 'KTEntryPoint' program into the software suite and placing that icon on the PC Desktop.
13
3732
by: Randy | last post by:
Is there any way to do this? I've tried tellg() followed by seekg(), inserting the stream buffer to an ostringstream (ala os << is.rdbuf()), read(), and having no luck. The problem is, all of these methods EXTRACT the data at one point or another. The other problem is there appears to be NO WAY to get at the actual buffer pointer (char*) of the characters in the stream. There is a way to get the streambuf object associated with the...
9
6504
by: apandapion | last post by:
I have an integer value inside a datarow. Is there a more graceful way to extract it than this: int value = Convert.ToInt32(datarow.ToString()); It's already an integer. Is there a way around the conversion?
3
21946
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 list of values that start in textboxes and listboxes that are both integers and strings. I need to store them in an array to pass to subs and stored procedures used in a database. Can I mix the integers and strings (both of varying lengths) in the...
2
4159
by: VictorTan | last post by:
Hello. I'm new to this forum. Hope that I don't make mistakes in here but if I do, please correct me if there is. Thanks. I also wanted to ask you guys regarding about the following following source codes I'm going to post it here as I did a search here and did not find any question related to mine. I'm doing an automatic inventory control system using RFID project and I'm instructed to extract the RFID transponder's ID and CRC and display...
4
3920
by: dexter48 | last post by:
Hi I'm searching for a string occurance in a text file. I find the string ok and write the results to a log file. But on the line above is also some information I need. How can i get that. The string occurs a number of times, but not an exact match for the string above. Can you help please: see code #!C:\\Perl\\bin use File::Copy; use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); ...
5
3644
by: Mukesh | last post by:
Hi, I am using framework 2.0. I am writing a foreach loop that will extract single dimensional arrays out of double dimensional array. I am trying writing something like this. string strDetails foreach(string str in strDetails) { //Code comes here }
0
8991
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...
1
9324
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
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8243
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
6074
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
4606
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...
1
3313
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
2783
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
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.