Thursday, May 3, 2012

String to Int ----- Int to String (some functions and their uses)

In many programming problems the input is given in string format and we have to extract int values from that for our manipulation... also sometimes we have to output some int in the form of a string .... following are the methods by which this task can be accomplished.....

1. Conversion from string to int 
suppose we are given a string time= "20:12:33";
int hour,min,second;
sscanf(time.c_str(),"%d:%d:%d",&hour,&min,&second);
now after the execution of above statement ,
 hour= 20, min= 12, second= 33

2. Conversion from string to int (when string is a set of two or more space separated strings)
suppose we have a string info= "Alice 20 M 125";
the above string consists of three strings(space separated) "Alice" , "20", "M", "125"
firstly include a header file..... #include<sstream>
make a declaration in your code istringstream is(info);
the example is shown below.....
#include<iostream>
#include<sstream>

void demo(string info)
                                                               {
istringstream is(info);
string name;
int age , id;
char sex;
is>>name; // name= Alice
is>>age; // age=20
is>>sex; // sex= M
is>>id; //id= 125
                                                                }


3. Conversion from int to string 
include a header file #include<sstream>,
example is shown below.......
#include<iostream>
#include<sstream>

                                                            void demo()
                                                           {
int hh=10, mm= 9, ss= 23;
                                                            stringstream t;
                                                            string time;
                                                            t<<hh<<":"<<mm<<":"<<ss;
                                                            time= t.str();// time= "10:9:23"
                                                            }



4. snprintf() in c++
#include<iomanip>
int totalrank=5;
double total= 234;
string name= "Piyush";
char buf[150];
vector<string> ans;
ans.clear();
snprintf(buf , sizeof(buf) , "%s %d %0.1f", name.c_str() , totalrank , total);
ans.push_back(buf);
cout<<ans[0];
the output would be......
Piyush 5 234.0











No comments:

Post a Comment