【问题标题】:c++ aligning the same word in a text file in different lines/positions to the same position in each linec ++将文本文件中不同行/位置中的相同单词对齐到每行中的相同位置
【发布时间】:2012-09-20 22:45:52
【问题描述】:

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

【问题讨论】:

  • 您必须至少向我们提供有关您如何尝试解决此问题的线索。我建议您先深入 Google 并编写一些最少的代码,然后再回来发布您尝试的解决方案。让我们看看您首先打开文件并找到指向“foobar”的所有指针位置。只有这样,我们的帮助才合理。这些都是提示,但不是答案。考虑完成任务所需的所有变量。这些回答的原因是这个问题听起来像是“做我的功课”。
  • 是的,很抱歉问了这么含糊的问题,我曾尝试用谷歌搜索,但找不到任何特定于我正在寻找的东西,并且对 C++ 的了解还不够,无法拼凑出什么去做。
  • 我正在尝试对齐已编译的文本或亚马逊销售以直接输入到 Excel 工作表中,但我想我只是想尝试研究 python 或 VBA 并完全取消对齐。感谢您的回复。干杯。

标签: c++ file io text-alignment


【解决方案1】:

来自的io操纵器std::setw()可用于在文本输出中创建定长列,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;
}

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

【讨论】:

    猜你喜欢
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 2021-08-20
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多