c++ - 如果我的输入超过多行,我需要输出也超过多行
问题描述
我创建了一个程序,可以反转句子中每个单词中的字母。我正在将文本输入超过 4 行的输入文本文件。输出文本都在 1 行,但我需要它这样当输入进入下一行时,输出也一样。
string reversed(string word)
{
int n;
for(int i=0; i<word.length()/2; i++)
{
swap(word[i],word[word.length()-1-i]);
}
return word;
}
int main()
{
ifstream in;
ofstream out;
in.open("input.txt");
out.open("output.txt");
string word;
while(in>>word){
out << reversed(word) << " ";
}
in.close();
out.close();
return 0;
}
输入示例:
期待世界善待你 公平,因为你是个好人 有点像期待公牛不会 攻击你,因为你是素食主义者。
输出示例:
gnitcepxE eht dlrow ot taert uoy ylriaf esuaceb uoy 时代 a doog nosrep si a elttil ekil gnitcepxe eht llub ton ot kcatta uoy euaceb uoy 时代 a nairategev。
解决方案
用于std::getline()
从输入中读取单独的文本行,然后使用 astd::istringstream
遍历每行的各个单词:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
std::string reversed(std::string word) {
std::reverse(word.begin(), word.end());
return word;
}
int main() {
std::ifstream in("input.txt");
std::ofstream out("output.txt");
std::string line, word;
while (std::getline(in, line)) {
std::istringstream iss(line);
if (iss >> word) {
out << reversed(word);
while (iss >> word) {
out << " " << reversed(word);
}
}
out << std::endl;
}
return 0;
}
推荐阅读
- ios - iOS13分享表:分享UIImage时如何设置预览缩略图
- javascript - 将数据属性添加到 Web 元素的最佳方式
- sql-server - 需要帮助将表的模式存储在 SSIS 中的变量中
- wordpress - 如何将导航标题菜单栏的背景颜色从一种颜色更改为两种颜色
- azure - 无法在 Azure (Windows) VM 中以交互模式运行 Docker
- sql - SQL 与 sqlalchemy.execute
- r - 带有 data.table 的引导功能
- java - Spring ScriptUtils - PostgreSQL 中未终止的美元报价
- ruby-on-rails - 使用 Vue 组件创建 Rails 表单
- c# - LINQ 知道如何连接字符串吗?