Need to chop code into functions

So I wrote this code that prompts users to create a .txt file that includes an array for a city population, and that the program has a search function afterwards.

My professor said it was good but she wanted me to use functions in this code. I've been staring at this for an hour or so and I'm having a really difficult time chopping this up and putting it into functions. I'm not sure if void functions will work with the file creation.

p.s. I'm at home and I don't have anything to test my code.

Any help is appreciated




#include <iostream>//including all needed libraries
#include <fstream>
#include <string>
using namespace std;//setting namespace std
using std::ifstream;//setting namespace for files



int main()
{
char filename[20];
string city[10], search;
int population[10];
int run=1,i=0,m=0,s=0;
std::ofstream file;
cout<<"What would you like to name the file?:\n";
cin>>filename;
file.open(filename);
while(run==1)
{
char input1[20];
int input2;
cout<<"enter city:\n";
cin>>input1;
file<<input1<<" ";
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
cout<<"enter population:\n";
cin>>input2;
file<<input2<<endl;
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
m++;
cout<<"would you like to add more cities?(1=yes, 0=no)\n";
cin>>run;
}
ifstream fileinput;
fileinput.open(filename);
while(i<=m)
{
fileinput>>city[i];
fileinput>>population[i];
i++;
}
fileinput.close();
cout<<"\nwhat city would you like to search for?\n";
cin>>search;
while(city[s]!=search)
{
s++;
}
cout<<"\ncity: "<<city[s]<<" population: "<<population[s]<<endl;
system("pause");
return 0;
}
Think about "sections" of the code that do general jobs. If you were to make a list of the tasks that this program does, that can help guide you where to split up the work into functions.
Thanks, that'll give me an idea of what I'm doing at least.
zhuge already said it, functions are used to do certain tasks.

this gets really useful, if you have to do a task several times, since you can just call the function with different input parameters, without the need to write the whole code again for each parameter.
Topic archived. No new replies allowed.