Lecture 7 example1: #include<iostream> using namespace std; int main() { const i
ID: 3694060 • Letter: L
Question
Lecture 7 example1:
#include<iostream>
using namespace std;
int main()
{
const int n = 20;
int i, j, x, y;
char numbers[n] = "2434:342";
char num[n];
// Find Colon Position
for(i = 0, j = 0; i < n && numbers[i] != ''; i++, j++)
{
// Copy Contents from one string to another
num[j] = numbers[i];
if(numbers[i] == ':')
{
// Make valid string, convert first number to integer
num[j] = '';
x = atoi(num);
j = -1; // Reset index
}
}
// Add String Terminator to make it a valid string
num[j] = '';
y = atoi(num);
// Display Results
cout << "x = " << x << ", " << "y = " << y << endl;
return 0;
}
1. In this exercise you need to process a raw data and extract some information. Your raw data is a string literal with following content: Name:grade1,grade2 For example John:78,64 You need to extract the name and the grades, and print them in the console, also you are required to calculate the average of these 2 grades and print it too. Note: You are required to use C-style String Hint: You can check the lec 7 example 1.Explanation / Answer
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
const int n = 100;
int i, j, first, second;
char data[n] = "John:78,64";
char num[n];
// Find Colon Position
for(i = 0; data[i] != ':'; i++)
num[i] = data[i];
num[i] = '';
cout<<"Name of the person is "<<num;
for(++i, j=0; data[i] != ','; j++, i++)
num[j] = data[i];
first = atoi(num);
for(++i, j=0; data[i] != ''; j++, i++)
num[j] = data[i];
second = atoi(num);
cout<<" Grade 1 is "<<first<<endl;
cout<<"Grade 2 is "<<second<<endl;
cout<<"Average is "<<(first+second)/2.0<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.