如何读取相邻字符串

how to read adjacent strings

本文关键字:字符串 读取 何读取      更新时间:2023-10-16

我是编程新手。有人能帮我怎么做吗。我的输入文件是这样的

运行

我需要得到这样的输出

狗是

正在运行

也就是说,我必须阅读相邻的单词对。我如何在C++中做到这一点?

这是我的新手C++方法(我只是C++的初学者)。我相信一个更有经验的C++开发人员会想出更好的东西:-)

#include <fstream>
#include <iostream>
#include <string>
int main()
{
    std::ifstream file("data.txt");    
    std::string lastWord, thisWord;
    std::getline(file, lastWord);
    while (std::getline(file, thisWord))
    {
        std::cout << lastWord << " " << thisWord << 'n';
        lastWord = thisWord;
    }
}

虽然我认为@dreamax已经显示了一些不错的代码,但我认为我会做一些不同的事情:

#include <fstream>
#include <string>
#include <iostream>
int main() { 
    std::string words[2];
    std::ifstream file("data.txt");
    std::getline(file, words[1]);
    for (int current = 0; std::getline(file, words[current]); current ^= 1)
        std::cout << words[current] << ' ' << words[current^1] << "n";
}

这稍微缩短了代码(有点不错),避免了不必要地复制字符串(更好)。