Question

In: Computer Science

#include <iostream> #include <string> #include <fstream> #include <vector> #include <sstream> using namespace std; int main() {...

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
ifstream infile("worldpop.txt");
vector<pair<string, int>> population_directory;
string line;
while(getline(infile, line)){
if(line.size()>0){
stringstream ss(line);
string country;
int population;
ss>>country;
ss>>population;
population_directory.push_back(make_pair(country, population));
}
}
cout<<"Task 1"<<endl;
cout<<"Names of countries with population>=1000,000,000"<<endl;
for(int i=0;i<population_directory.size();i++){
if(population_directory[i].second>=1000000000){
cout<<population_directory[i].first<<endl;
}
}
cout<<"Names of countries with population<=1000,000"<<endl;
for(int i=0;i<population_directory.size();i++){
if(population_directory[i].second<=1000000){
cout<<population_directory[i].first<<endl;
}
}
}

can u pls explain the logic behind this code up to 10 lines pls, many thanks

Solutions

Expert Solution

The best way to explain the working of this program is to explain how each line of code works. For that I have added comments on every important line of code in this program. Check it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: To put things simply, this program opens a file that stores country names and populations in the format <country name><space or tab><population> on each line, and display names of countries with population above or equal to 1000,000,000 and then the names of countries with population below or equal to 1000,000.

//including needed libraries
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
        //opening worldpop.txt file in read mode, assuming file exists.
    ifstream infile("worldpop.txt");
    //creating a vector of pair objects. each pair has first value of type string and 
    //second value of type int.
    vector<pair<string, int> > population_directory;
    //a string variable to hold a single line
    string line;
    //looping as long as a line is successfully read from file (will keep looping until
        //the end of file)
    while (getline(infile, line)) {
        //ensuring that line is not blank
        if (line.size() > 0) {
                //creating a stringstream object to tokenize the line (to split into individual words/values)
            stringstream ss(line);
            //defining two variables to store country name and population
            string country;
            int population;
            //reading country and population from ss object. 
            //for example, if the line is "Alabama 1234567", then "Alabama" is stored in country and 
            //1234567 is stored in population
            ss >> country;
            ss >> population;
            //make_pair method will create and return a pair object of given two values. so here we create
            //a pair object of country and population, add that pair to the end of population_directory
            //vector.
            population_directory.push_back(make_pair(country, population));
        }
    }
    
    //always remember to close the file once done.
    infile.close();
    
    //now we will display the countries with population >= 1000,000,000
    cout << "Task 1" << endl;
    cout << "Names of countries with population>=1000,000,000" << endl;
    
        //looping through each index in population_directory vector
        for (int i = 0; i < population_directory.size(); i++) {
                //each pair has the attributes first and second, where first points to the country name
                //and second points to the population. here we check if population is above the target
                //for pair at index=i in vector
        if (population_directory[i].second >= 1000000000) {
                //yes, in which cas we print country name (first attribute of pair)
            cout << population_directory[i].first << endl;
        }
    }
    
    //now we repeat the same process to display countries with population <= 1000,000
    cout << "Names of countries with population<=1000,000" << endl;
    for (int i = 0; i < population_directory.size(); i++) {
        if (population_directory[i].second <= 1000000) {
            cout << population_directory[i].first << endl;
        }
    }
}

Related Solutions

#include <iostream> #include <fstream> #include <string> using namespace std; const int QUIZSIZE = 10; const int...
#include <iostream> #include <fstream> #include <string> using namespace std; const int QUIZSIZE = 10; const int LABSIZE = 10; const int PROJSIZE = 3; const int EXAMSIZE = 3; float getAverage(float arr[], int size) { float total = 0; for (int i = 0; i < size; i++) { total += arr[i]; } return total/size; } // the following main function do.... int main() { ifstream dataIn; string headingLine; string firstName, lastName; float quiz[QUIZSIZE]; float lab[LABSIZE]; float project[PROJSIZE]; float midExam[EXAMSIZE];...
9. #include <fstream> #include <iostream> using namespace std; int main() {     float bmi;     ifstream...
9. #include <fstream> #include <iostream> using namespace std; int main() {     float bmi;     ifstream inFile;     inFile.open("bmi.txt");     while (!inFile.eof())       {          inFile >> bmi;          if( bmi < 18.5)           {               cout << bmi << " is underweight " ;           }         else if( bmi >= 18.5 && bmi <= 24.9)           {               cout << bmi << " is in normal range " ;           }         else if( bmi >= 25.0 &&...
Complete the following program #include<iostream> #include<iomanip> #include<fstream> using namespace std; int main() { // I -...
Complete the following program #include<iostream> #include<iomanip> #include<fstream> using namespace std; int main() { // I - Declaring a five by five array /* II - Read data from data.txt and use them to create the matrix in the previous step*/    // III - Count and print the number of even integers in the matrix. /* IV - Calculate and print the sum of all integers in the columns with an even index value. Please note the column index begins...
#include <iostream> #include <string> #include <iomanip> #include <fstream> using namespace std; struct Product {    string...
#include <iostream> #include <string> #include <iomanip> #include <fstream> using namespace std; struct Product {    string itemname;    int id;    string itemcolor;    double cost; }; void fillProduct(Product[10], int& );//read data from a file and store in an array void writeProduct(Product[10], int);//write the array into a file void writeBinary(Product[10], int);//write the array into a file in binary mode void printbinary(Product[10], int);//read data from the binary file and print int main() {    Product myList[10];    int numItems = 0;...
#include <iostream> #include <fstream> #include <vector> using namespace std; struct Point{ int x, y; bool operator==(const...
#include <iostream> #include <fstream> #include <vector> using namespace std; struct Point{ int x, y; bool operator==(const Point& p2) { return this->x == p2.x and this->y == p2.y; } bool operator!=(const Point& p2) { return this->x != p2.x or this->y != p2.y; } friend ostream &operator<<( ostream &out, const Point &P ) { out << "(" << P.x << ", " << P.y << ")"; return out; } friend istream &operator>>( istream &in, Point &P ) { char d1, d2, d3;...
#include <iostream> #include <string> #include <array> #include <vector> using namespace std; void f(int x, int &y);...
#include <iostream> #include <string> #include <array> #include <vector> using namespace std; void f(int x, int &y); int main(){ char s1[] = "zoey"; char s2[] = "zoey"; string s3 = s1; string s4 = s2; cout << "1. sizeof(s1) = " << sizeof(s1) << endl; if(s1 == s2) cout << "2. s1 == s2 is true" << endl; else cout << "2. s1 == s2 is false" << endl; if(s3 == s4) cout << "3. s3 == s4 is true" <<...
9. #include <fstream> #include <iostream> using namespace std; int main() { float bmi; ifstream inFile; inFile.open("bmi.txt");...
9. #include <fstream> #include <iostream> using namespace std; int main() { float bmi; ifstream inFile; inFile.open("bmi.txt"); while (!inFile.eof()) { inFile >> bmi; if( bmi < 18.5) { cout << bmi << " is underweight " ; } else if( bmi >= 18.5 && bmi <= 24.9) { cout << bmi << " is in normal range " ; } else if( bmi >= 25.0 && bmi <= 29.9) { cout << bmi << " is overweight " ; } else...
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string userInput; getline(cin, userInput);...
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string userInput; getline(cin, userInput); // Declaring base int N = 30; if (userInput.length() > 10) { cout << 0 << endl; } else { int finalTotal = 0; //Iterates through userInput for(int i = 0; i < 10; i++){ char convertedInput = userInput[i]; // ASCII decimal value of each character int asciiDec = int(convertedInput); //Casts char value from input to int value stringstream chr; chr << convertedInput; int...
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to...
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to store user input bool cont = true; //implement a loop so that it will continue asking until the user provides a positive integer // the following provides ONLY part of the loop body, which you should complete { cout <<"How many words are in your message? \n"; cout <<"Enter value: "; // get user input integer here    cout <<"\nInvalid value. Please Re-enter a...
#include <cstring> #include <stdio.h> #include <iostream> using namespace std; int main() {        const int...
#include <cstring> #include <stdio.h> #include <iostream> using namespace std; int main() {        const int SIZE = 20;     char str[SIZE];     char str1[SIZE];     int n;     int k =1;        printf("Enter a word: \n");     fgets(str,SIZE,stdin);     printf("Enter another word: \n");     fgets(str1,SIZE,stdin);        if (str1[strlen(str1) - 1] == '\n')     {         str1[strlen(str1)-1] = '\0';     }     if (str[strlen(str) - 1] == '\n')     {         str[strlen(str)-1] = '\0';     }      ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT