首页 > 解决方案 > 如果我的输入超过多行,我需要输出也超过多行

问题描述

我创建了一个程序,可以反转句子中每个单词中的字母。我正在将文本输入超过 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。

标签: c++

解决方案


用于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;
}

现场演示


推荐阅读