﻿ Convert string to number and vice versa

## Convert string to number and vice versa

When you are writing a computer program, you might want to convert a string to number or vice versa. This might be a problem for C++ beginners. This tip helps you to solve this problem.

In C++, you can use the atoi, atol, atof, and strtod functions to convert a string to integer, long, float, and double numbers respectively. In contrast, you will use the str() method of the ostringstream class to convert a number to string. The ostringstream class is in the sstream header file. You need to include this header file by adding the line: #include<sstream> to the header section of your program.

In the example program keeps data of a number of students. Each student contains id, name, final score, and mid-term score. These data are string values that will be input by user. A two-dimensional array is used to store the data. After the data are input, the program will display the data in a table. This table also includes the total scores of each student. A total score is calculated by adding the final and mid-time scores together.

#include<iostream>
#include<sstream>
using namespace std;

void st(int n){

int c=5;
string ar[n][c];
char con='y';
int i=0;
while((con!='n') && (i<n)){
cout<<"id:";
cin>>ar[i];
cout<<"name:";
cin>>ar[i];
cout<<"final score:";
cin>>ar[i];
cout<<"mid score:";
cin>>ar[i];
i++;
cout<<"Press y to continue or n to stop:";
cin>>con;

}
int j=0;
while(j<i){
ostringstream oss;
oss<<strtod(ar[j].c_str(),NULL)+strtod(ar[j].c_str(),NULL);
ar[j]=oss.str();

j++;
}

for(int r=0;r<i;r++)
{
for(int c=0;c<5;c++)
cout<<ar[r][c]<<"\t";
cout<<"\n";
}

}
int main()
{

st(2); //two students for an example

system("PAUSE");
return 0;
} Posted by: Dara | post date: 12-31-2013 | Subject: C++ Programming Language This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.