C++ 将文本文件中不同行/位置的相同单词与每行中的相同位置对齐
c++ aligning the same word in a text file in different lines/positions to the same position in each line
我想知道如何浏览文本文件并在每行的不同位置找到给定的单词("foobar"),然后将单词重新对齐到新文本文件中的相同位置,如果这没有意义,请告诉我。
***in text file***
1 foobar baz
2 foobar baz
3 foobar baz
****out text file***
1 foobar baz
2 foobar baz
3 foobar baz
io 操纵器 std::
setw() from 可用于在文本输出中创建固定长度的列,std::setfill() 用于指定填充字符:
std::cout << std::setw(5) << std::setfill('0') << 5 << std::endl;
将打印:
00005
这可以很容易地用于创建一个小程序,该程序从一个文件读取所有行并将它们写入另一个文件,同时对齐所有列(在下面的程序中>>用于读取一列,这意味着 in 文件中的列应该由一个或多个空格字符分隔):
#include <iostream>
#include <iomanip>
#include <vector>
#include <fstream>
#include <map>
#include <algorithm>
int main (int argc, char* arv[])
{
using namespace std;
std::vector<std::vector<std::string> > records;
std::map<int, int> column_widths;
std::ifstream in_file("infile.txt", std::ios::text);
if (!in_file.is_open())
return 1;
std::ofstream out_file("outfile.txt", std::ios::text);
if (!out_file.is_open())
return 2;
// read all the lines and columns into records
std::string line;
while (std::getline(in_file, line)) {
std::istringstream is(line);
std::vector<std::string> columns;
std::string word;
int column_index = 0;
while (is >> word) {
columns.push_back(word);
column_widths[column_index] = std::max(column_width[column_index], word.length());
++column_index;
}
records.push_back(columns);
}
// now print all the records and columns with fix widths
for (int line = 0; line < records.size(); ++line) {
const std::vector<std::string>& cols = records[line];
for (int column = 0; column < cols.size(); ++column) {
out_file << std::setw(column_widths[column])
<< std::setfill(' ')
<< cols[column] << ' ';
}
out_file << "n";
}
return 0;
}
我没有编译程序,但它应该:)工作。
相关文章:
- 文本文件中的单词链表
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 在指针的帮助下,文本文件中单词的频率
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何根据单词在文本中出现的概率输出单词
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 替换字符串位置 X 中的单词C++
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何使用向量 c++ 迭代文件中单词的位置
- 如何在任何位置阅读和替换C++单词
- C++ 将文本文件中不同行/位置的相同单词与每行中的相同位置对齐
- 通过在每个位置从特定位置的单词池中选择单词,有效地生成所有序列
- 如何逐字阅读文件并找到每个单词的位置
- 突出显示qtextedit中x和y作为位置的单词
- 从字符串中获取一个单词,对其进行更改,然后将其放回正确的位置