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.

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<<"final score:";
           cout<<"mid score:";
           cout<<"Press y to continue or n to stop:";
       int j=0;
               ostringstream oss;
       for(int r=0;r<i;r++)
             for(int c=0;c<5;c++)

int main()

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


Posted by: Dara | post date: 12-31-2013 | Subject: C++ Programming Language

write programming tip

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.