首页 > 解决方案 > 问题是我需要输入字符串来接受空行

问题描述

该程序应该接收一个字符串,该字符串可以包含空行、空格和换行符。所以问题是我不能使用get line,因为我不知道用户将使用多少条断线。我试着做一会儿,但没有用,程序停止工作。这是一段时间,它将接收一个字符并在字符串中使用推回插入,而字符与 EOF 不同。我不知道该怎么做,或者为什么这样做不起作用。此代码使用 get 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;
}
''''

标签: c++11

解决方案


两种可能的解决方案:

#include <iostream>
#include <string>
int main(){
    std::string line;
    while(std::cin >> line){
        //Variable line contains your input.
    }
    //Rest of your code
    return 0;
}

或者:

#include <iostream>
#include <string>
int main(){
    std::string line;
    while(std::getline(std::cin, line)){
        if (line.empty()){
            break;
        }
        //Variable line contains your input.
    }
    //Rest of your code
    return 0;
}

推荐阅读