vendredi 29 mars 2019

The problem is i need the input of the string to accept a blank line

The program is supposed to receive a string, that can have blank lines, blank spaces, and break lines. So the problem is i can't use get line, because i don't know how many break lines the user will use. I tried making a do while but it didn't work, the program stops working. It was a do while, that would receive an char and using pushback insert in the string while the char was different to EOF. I don't know how else to do it, or why this do while doesn't work. This code is using get line witch doesn't accept a break line.

'''''
#ifndef INDICE_H
#define INDICE_H
#include <cstddef>

struct Indice{
    std::size_t f;
    double p;
};

#endif
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <map>
#include "Indice.hpp"

int main()
{
    std::string str;
    std::getline(std::cin, str);

    // Count the number of occurrences for each word
    std::string word;
    std::istringstream iss(str);
    std::map<std::string,Indice> occurrences;
    while (iss >> word) ++occurrences[word].f;

    //Calculate the percentual each word
    int total = 0.0;
    for (std::map<std::string,Indice>::iterator it = occurrences.begin(); 
         it != occurrences.end(); ++it)
    {
        total += it->second.f;
    }

    for (std::map<std::string,Indice>::iterator it = occurrences.begin(); 
         it != occurrences.end(); ++it)
    {
        it->second.p = (static_cast<double>(it->second.f))/total;
    }
    // Print the results
    for (std::map<std::string,Indice>::iterator it = occurrences.begin(); 
         it != occurrences.end(); ++it)
    {
        if(it->first.size()>2)
            std::cout << it->first << " " << it->second.f  << " "<< std::fixed << std::setprecision(2) << it->second.p << std::endl;
    }

    return 0;
}
''''

Aucun commentaire:

Enregistrer un commentaire