繁体   English   中英

用空白填充二维数组(从文件输入)

[英]Filling a 2D array with white space (input from file)

我在向二维数组“项目”中添加空白时遇到了问题。 最后,我基本上希望文件 (quote.txt) 中的数据能够使用其行号正确索引。 我已经将数组 9(行)乘以 20(列),这是我文件中最大的句子,并且在没有 20 列数据单元的地方我想用空格填充它,这样我就可以相应地索引我的数组。

我试过使用向量的向量,但它变得非常混乱。

  #include <iostream>
  #include <sstream> 
  #include <fstream>
  #include <vector>
  #include <array>
  #include <string>

  using namespace std;


  int main() 
  {
  string file_name;
  ifstream fin("quote.txt");
  while(!fin)
  {
      cout << "Error Opening File! Try again!" << endl;
      cout << "Enter file name: ";
      cin >> file_name;
  }
  string item[9][20];

  for (int row = 0; row < 9; row++) 
  {
      for (int col = 0; col < 20; col++)
      {
          fin >> item[row][col]; 
        //cout << item[row][col] << endl;

      }
  }
  for (int k = 0; k < 20; k++)
  {
    cout << item[0][k] << endl;
  }

  }

说明:我试图用quote.txt 中的内容填充我的项目2d 数组,但由于句子长度不同,我不能使用for 循环并说列是20 个单位,因为它渗入下一行并搞砸了索引。 我的解决方案是我想添加一个空格(填充符),以便我可以使用 for 循环进行迭代,并且每行中的每个内容都有 20 列。 这样我就可以使用行索引来查看文本文件中的每一行。 基本上,我希望文本文件是一个二维数组,我可以在其中通过使用 [row][col] 索引找到每个元素(单词)。

文本文件:“quote.txt”

    People often say that motivation doesn  t last   Well   neither does bathing that s why we recommend it daily   Ziglar
    Someday is not a day of the week      Denise Brennan  Nelson
    Hire character   Train skill      Peter Schutz
    Your time is limited   so don t waste it living someone else s life      Steve Jobs
    Sales are contingent upon the attitude of the salesman      not the attitude of the prospect      W   Clement Stone
    Everyone lives by selling something      Robert Louis Stevenson
    If you are not taking care of your customer   your competitor will      Bob Hooey
    The golden rule for every businessman is this: Put yourself in your customer s place      Orison Swett Marden
    If you cannot do great things do small things in a great way    Napoleon Hill

该程序应该做什么?

该程序假设允许我通过用户输入查找单词。 说这个词是“of”,它应该输出它所在的行号。 同样,如果我输入“of People”,它会输出行号

我可能会这样做:

// The dynamic vector of strings from the file
std::vector<std::vector<std::string>> items;

std::string line;

// Loop to read line by line
while (std::getline(fin, line))
{
    // Put the line into an input string stream to extract the "words" from it
    std::istringstream line_stream(line);

    // Add the current line to the items vector
    items.emplace_back(std::istream_iterator<std::string>(line_stream),
                       std::istream_iterator<std::string>());
}

在此之后, items向量将包含所有行上的所有单词。 例如, items[1]将是第二行, items[1][2]将是第二行的第三个单词( "not"与您显示的文件内容)。


按照程序的既定目的(在文件中查找单词或短语,并报告在哪些行号上找到它们),您根本不需要存储这些行。

您需要做的就是将每一行读入一个字符串,用一个空格替换所有制表符和多个空格,然后查看是否在该行中找到了单词(或短语)。 如果找到,则将行号存储在向量中。 然后在阅读下一行时丢弃当前行。

处理完所有文件后,只需报告向量中的行号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM