C++ 将文本文件中不同行/位置的相同单词与每行中的相同位置对齐

c++ aligning the same word in a text file in different lines/positions to the same position in each line

本文关键字:位置 单词 对齐 文本 C++ 文件      更新时间:2023-10-16

我想知道如何浏览文本文件并在每行的不同位置找到给定的单词("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;
}

我没有编译程序,但它应该:)工作。