Can this code be rewritten so that a switch statement isn\'t use but a loop inst
ID: 3591074 • Letter: C
Question
Can this code be rewritten so that a switch statement isn't use but a loop instead. Thanks.
#include
#include
#include
using namespace std;
int main()
{
int N=0;
string s; //to read lines from file
int count[10]={0,0,0,0,0,0,0,0,0,0}; //initialize all digit counts to zeroes
string filename; //to store filename
//ask user to enter filename
cout<<"Enter a filename to analyze"<
cin>>filename;
//open inputfile
ifstream inputfile;
inputfile.open(filename.c_str());
//read firstline
inputfile>>s;
while(s!="-1"){
N++; //count total lines (Numbers)
int start_digit=s[0] - '0'; //take first digit of each string
//increment respective count
switch(start_digit){
case 0:
count[0]+=1;
break;
case 1:
count[1]+=1;
break;
case 2:
count[2]+=1;
break;
case 3:
count[3]+=1;
break;
case 4:
count[4]+=1;
break;
case 5:
count[5]+=1;
break;
case 6:
count[6]+=1;
break;
case 7:
count[7]+=1;
break;
case 8:
count[8]+=1;
break;
case 9:
count[9]+=1;
break;
}
inputfile>>s;
}
cout<
cout<<"N="<
//print count and percentage
for(int i=0;i<10;i++){
cout<
}
inputfile.close(); //close input file
return 0;
}
Explanation / Answer
The switch statement can be replaced with following loop statement.
for (i = 0; i<10; i++){
if (start_digit == i){
count[i] +=1;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.