如何读取相邻字符串
how to read adjacent strings
我是编程新手。有人能帮我怎么做吗。我的输入文件是这样的
狗
是
运行
我需要得到这样的输出
狗
狗是
正在运行
也就是说,我必须阅读相邻的单词对。我如何在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";
}
这稍微缩短了代码(有点不错),避免了不必要地复制字符串(更好)。
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何从字符串C++读取多个整数
- 使用字符串读取的字符串
- 从文件到字符串读取并传递到功能
- C++ cin 将字符串读取到 int 类型中返回 0
- 使用CIN和/或字符串读取带有混合输入的文本文件
- 将两个字符串作为一个字符串读取
- 如何将WCP 1252字符串读取为std::tstring
- 如何将字符串读取为字符串向量或将整数读取为整数向量
- 将一系列字符串读取到char数组中
- 如何在 c++ 中将文件中的段落作为单个字符串读取
- 从 txt 文件中将后缀表达式作为字符串读取
- C++银行项目;如何将一组字符串读取为单独的浮点数并添加它们
- 在 c++ 中循环字符串读取器
- 将字符串读取为命令行参数C++
- 如何在QT中使用QDomDocument对象将字符串读取为XML
- 使用Matio库将.mat文件中的字符串读取到C++中
- 作为字符串读取第一列数据文件
- 如何在字符串读取完成时停止c++的recv() ?