CSI 250L Lab 2 Solution, Spring 2012
American University of Science and Technology · Programming II Lab · 2 pages · Dr. Saeed Raheel · with solution
More CSI 250L files
- Lab 1 Solution · Spring 2012Lab · with solutionView
- Lab 1 · Spring 2012LabView
- Lab 10 Solution · Spring 2012Lab · with solutionView
- Lab 10 · Spring 2012LabView
- Lab 11 Solution · Spring 2012Lab · with solutionView
- Lab 11 · Spring 2012LabView
- Lab 12 Solution · Spring 2012Lab · with solutionView
- Lab 12 · Spring 2012LabView
Show the text of this lab
American University of Science & Technology
Department Of Computer Science
CSI 250L – Computer Programming-II Lab
Fall 2011/2012
Lab Work 2
Solution provided by : Dr. Saeed Raheel
Problem 4:
Write a program to input a line of text and store it in an array Line. The program should
allow the user to choose from the following menu:
1- Count the number of words in Line.
2- Output the length of Line.
3- Append “***” to Line.
4- Output the content of Line.
5- Exit.
#include <iostream>
using namespace std;
int countWords(char a[])
{
int count=0;
for (int i=0;a[i]!='\0';i++)
if (a[i]==' ') ++count;
++count; // to account for the last word in the line (usually it
is not followed by a space but rather \0)
return count;
}
int getLength(char a[])
{
int i;
for (i=0;a[i]!='\0';++i);
return i;
}
void printArray(char a[])
{
for (int i=0;a[i]!='\0';++i)
cout << a[i];
}
1
void appendStars(char a[])
{
int size = getLength(a);
a[size]='*';
a[size+1]='*';
a[size+2]='*';
a[size+3]='\0';
}
int main()
{
const int size = 80;
char Line[size];
int action = 0;
cout << "Please enter a line of text : ";
cin.getline(Line, size);
while (action!=5)
{
cout << "Please choose one of the following actions : " <<
endl;
cout << "1- Count the number of words in Line." << endl;
cout << "2- Output the length of Line." << endl;
cout << "3- Append \"***\" to Line." << endl;
cout << "4- Output the content of Line." << endl;
cout << "5- Exit." << endl << endl;
cin >> action;
switch (action)
{
case 1: cout << "The number of words in \"" << Line
<< "\" : " << countWords(Line)<< endl;break;
case 2:cout << "The length of \"" << Line << "\" : "
<< getLength(Line)<< endl;break;
case 3:cout << "Appending \"***\" to \"" << Line <<
"\" : "; appendStars(Line); printArray(Line); cout << endl;break;
case 4:cout << "The line of text is \"";
printArray(Line); cout << "\"" << endl;break; // or simply cout << Line
case 5:cout << "Exiting...Bye Bye" << endl;break;
default : cout << "Invalid choice!" << endl;
}
cout << endl;
}
system("pause");
return 0;
}
2