Answer to Question #192439 in C++ for Anuj

Question #192439

Input a string from user in the following format:  Name_RollNo_GPA.

Now perform string tokenization operation on this string to separate the Roll no and GPA. Store each token in a separate row of 2d char array and then print that string. Plus store name in a string, roll no in integer and GPA in float. And also print them. You are not allowed to use atoi() and atof().

 

Note: You cannot call built in function of strtok()

 



1
Expert's answer
2021-05-13T19:03:04-0400
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string user_str;
	char token[3][50];
	int row = 0;
	int col = 0;
	cout << "Enter your string: ";
	getline(cin, user_str);
	for (int i = 0; i < user_str.length(); i++)
	{
		if (user_str[i] == '_') 
		{
			token[row][col] = '\0';
			row += 1;
			col = 0;
		}
		else
		{
			token[row][col] = user_str[i];
			col += 1;
		}
	}
	token[row][col] = '\0';
	cout << "Outputting strings of a two-dimensional character array" << endl;
	for (int i = 0; i < 3; i++) 
	{
		for (int j = 0; token[i][j] != '\0'; j++) 
		{
			cout << token[i][j];
		}
		cout << endl;
	}
	string name = "";
	int roll_no{ 0 };
	float  gpa{ 0 };
	for (int i = 0; token[0][i] != '\0'; i++) 
	{
		name = name + token[0][i];
	}
	cout << "name: " << name << endl;
	for (int i = 0; token[1][i] != '\0'; i++) 
	{
		roll_no *= 10;
		roll_no += token[1][i] - 48;
    }
	cout << "RollNo: " << roll_no << endl;
	for (int i = 0; token[2][i] != '\0'; i++) 
	{
		if (token[2][i] == '.') 
		{
			int d = 10;
			for (int j = i + 1; token[2][j] != '\0'; j++) 
			{
				gpa +=( (token[2][j] - 48.0) / d);
				d *= 10;
			}
			break;
		}
		gpa *= 10;
		gpa += (token[2][i] - 48);
	}
	cout << "Gpa: " << gpa << endl;
	return 0;


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment