一旦到达行尾,停止向2D数组中输入文本

C++ Stop inputting text into 2D array once it reaches the end of the line

本文关键字:2D 数组 文本 输入      更新时间:2023-10-16

我搜索了一遍,又读了一遍,但还是不明白。我只是试图输入一个文本文件到一个[I][j]字符串数组。它做得很好,但是我需要它在到达行尾时停止向数组输入并开始将第二行放到第二个数组中,在行尾停止等等。

我的文件包含4个独立的行,如下所示:

这是第一行
这是第二行。
这是第三行。
这是第四行。

我的代码读取它,并主要做我需要它做的事情。但是它将所有内容放入数组中,直到空间用完,然后继续到下一行。一旦到达第一行,它就不会停止。这是我的代码。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    string arrayTextIn[25][25];
    ifstream textIn;
    textIn.open("sampleText.txt");
    for(int i=0; i<25; i++)
        for(int j=0; j<25; j++)
    {
        textIn >> arrayTextIn[i][j];
            if(arrayTextIn[i][j] == "n") //This is where I dont know how to proceed.
                break;
    }
    for(int i=0; i<25; i++)
        for(int j=0; j<25; j++)
           cout << i << " " << j << " "<< arrayTextIn[i][j] << endl;
    return 0;
}

这是输出,但我想要的是每行从新的[第i]行开始。谢谢你的帮助。
0 0这个
1是
0 2 line
1 .
0 4这个
5 .
0 6 line
2 .
0 8这个
9是
0 10 line
3 .
0 12这个
13是
0 14 line
4 .
16 0
1 0
1
1 2
1 3
4

这是一个两步的过程。

第一步是读取输入,一次一行,这将是读取输入文件中的每行文本:

ifstream textIn;
textIn.open("sampleText.txt");
for(int i=0; i<25; i++)
{
    std::string line;
    if (std::getline(textIn, line).eof())
        break;
    // Magic goes here.
}

那么,到目前为止,我们所完成的就是读取每一行输入,最多读取25行

第二步是取每一行输入,并将其分成以空格分隔的单词。

std::istringstream iline(line);
for(int j=0; j<25; j++)
{
    std::string word;
    if ((iline >> word).eof())
        break;
    arrayTextIn[i][j]=word;
}

首先构造一个istringstream,它的工作原理与ifstream完全相同,只是输入流来自字符串。

然后,它几乎和你最初的一样,只是现在作用域变小了,可以很容易地用一个循环来处理。

总之:处理任何中等复杂程度的任务的方法是将其分成两个或多个较小的任务。在这里,您将这个相对复杂的任务转化为两个更小、更容易实现的任务:首先,读取每一行文本,其次,给定一行已读文本,将每行划分为单独的单词。

如果你真的想保持你的设计(2D-array),那么这可能是一个快速的解决方案:

for (int i = 0; i < 25; i++) {
  std::string line;
  std::getline(textIn, line);  // read the entire line
  if (textIn.eof()) {
    // if reach the end of file, then break the cycle.
    break;
  }
  if (line.size() > 0) {  // avoid empty lines
    int j = 0;
    size_t finder;
    // Cycle and looking for whitespace delimiters.
    while (finder = line.find(' '), finder != std::string::npos && j < 25) {
      // get a single word
      auto token = line.substr(0, finder);
      if (token != " ") {
        // if that word is not a simple white-space then save it in the array. You can also std::move if C++11
        arrayTextIn[i][j] = token;
        ++j;
      }
      // erase that part from the main line
      line.erase(0, finder + 1);
    }
  }
}