c++11 - 问题是我需要输入字符串来接受空行
问题描述
该程序应该接收一个字符串,该字符串可以包含空行、空格和换行符。所以问题是我不能使用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;
}
''''
解决方案
两种可能的解决方案:
#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;
}
推荐阅读
- laravel - 我没有加入 ad_categories 表的数据
- laravel - 如何在 Heroku 中为自定义域生成 ssl 证书的 CSR?
- python - 使用arabic-reshaper和python-bidi(在多行情况下)时如何修复反向行?
- r - 使用一个命令仅显示特定统计数据(中位数、平均值、标准差、变量、最小值、最大值、分位数)。没有额外的统计数据
- python - Django Query 将多个 ArrayFields 组合成一个文本字符串
- lua - 一个函数如何在表的字段中导航
- javascript - 画布中没有渲染任何内容
- javascript - 异步操作回调必须只运行一次吗?
- haskell - Coq:haskell 的 Replicate 函数的强规范
- reactjs - 组件未更新 - 如何使用密钥的问题