简体   繁体   English

在C ++中从.txt文件中查找垂直词

[英]Finding a vertical word from a .txt file in C++

I am working on a small project and I am trying to put a set of letters (5 rows, 5 columns) from a .txt file into an array, then finding the vertical word "DOG." 我正在做一个小项目,我正在尝试将.txt文件中的一组字母(5行,5列)放入数组中,然后找到垂直单词“ DOG”。 Not only do I have to find it, but I have to determine the position of the word also. 我不仅必须找到它,而且还必须确定单词的位置。 I am having so much trouble getting it to complete this task. 我很难完成它。

1) It doesn't matter if I take the word DOG out or not. 1)我是否带出“狗”一词都没有关系。 My code still says it finds the word. 我的代码仍然说找到了这个词。

2) It always displays the same position if I move the word DOG to another spot on the puzzle. 2)如果我将“狗”一词移到拼图上的另一个位置,它将始终显示相同的位置。

3) It just doesn't work... 3)就是行不通了...

Can any of you help? 你们有什么可以帮助的吗?

Please keep in mind, this is my 2nd week of C++. 请记住,这是我C ++的第二周。 I am currently taking an intro college course on this language so no hate. 我目前正在使用该语言进行大学入门课程,所以不要讨厌。 I am only trying to learn. 我只是想学习。 I spent probably a total of 12 hours on this code. 我大概花了12个小时在这段代码上。

#include <iostream>
#include <fstream>

using namespace std;

int main() {
  char puzzle[25];
  ifstream fin;
  fin.open("words.txt");

  int rows {5};
  int cols {5};

  for (int i=0;i<rows*cols;i++) fin >> puzzle[i];
  fin.close();

/***********
 This is what I believe the array looks like and the values of each position.

 * 0   1   2  3   4
 * 5   6   7  8   9
 * 10  11  D  13  14
 * 15  16  O  18  19
 * 20  21  G  23  24
************/

string s = "DOG";
cout << s.size() << endl;
int foundpos {-1};

for (int i=0; i<rows*cols; i++) {
  if (puzzle[i]==s[0]) {
        foundpos=i;
        for (int j=5; j<s.size(); j+5) {
          if (puzzle[i+j]!=s[j]) {
                foundpos=-1;
                break;
          }
        }
 }

     if (foundpos>0) {
        cout << s << " was found at pos " << foundpos << endl;
        cout << s << " found on row " << foundpos << endl;
        cout << s << " found on column " << foundpos << endl;
        break;
     }
 }

 if (foundpos==-1) cout << s << " not found." << endl;

 return 0;
}

=============================================================== ================================================== =============

Now here is the .txt file. 现在这是.txt文件。

YRUVG RTSDC IFDYU EPOWE PWGHT YRUVG RTSDC IFDYU EPOWE PWGHT

Your problem is here: 您的问题在这里:

for (int j=5; j<s.size(); j+5) {
          if (puzzle[i+j]!=s[j]) {
                foundpos=-1;
                break;
          }
        }

Your idea: when you get the first letter of given string, you try to check the next letter of same column is same with the next letter of given string. 您的想法:当您得到给定字符串的第一个字母时,您尝试检查同一列的下一个字母是否与给定字符串的下一个字母相同。 But, you ran the loop from 5, note that s.size() = 3 , so your loop does NOT run. 但是,您从5开始运行循环,请注意s.size() = 3 ,因此循环不会运行。 Then, the foundpos is not set to -1 . 然后, foundpos未设置为-1 That's why you always see 8 in print log. 这就是为什么您总是在打印日志中看到8的原因。

Fix: 固定:

for (int j=1; j<s.size(); j++) {
          if (puzzle[i+j*5]!=s[j]) {
                foundpos=-1;
                break;
          }
        }

There were a few other caveats that you would need to address that I was unable to include in the comments. 您还需要解决一些其他警告,但我无法在评论中添加这些警告。 Since you are reading all characters into a single array which you want to represent as a 2D array, you will need to index puzzle[i][j] as puzzle[i + j * STRIDE] . 由于您正在将所有字符读取到一个要表示为2D数组的单个数组中,因此需要将puzzle[i][j]索引为puzzle[i + j * STRIDE]

The primary approach is to loop over each character is puzzle checking whether the first character in your search term is the current character. 遍历每个字符的主要方法是puzzle检查您搜索词中的第一个字符是否为当前字符。 If it is, you check: 如果是,则检查:

  1. Do enough character remain between i and rows*col for the rest of the search term to exist in a column? irows*col之间是否保留足够的字符以使其余搜索词存在于列中? If not, you can conclude your string is not found; 如果没有,您可以断定找不到您的字符串。
  2. If enough character remain, set a found = true flag and loop over the remaining characters in your search term (eg from j = 1 to term.size() ) checking puzzle[i + j * STRIDE] != term[j] if a non-matching term is found, set found = false and break the term loop; 如果剩余足够的字符,则设置一个found = true标志,并在搜索词中其余字符(例如,从j = 1term.size() )上term.size()检查puzzle[i + j * STRIDE] != term[j]找到不匹配的术语,将found = false设置found = false并中断术语循环; and
  3. finally check the found flog. 最后检查found鞭f。 If it has survived as found == true at this point, your search term has been found and you can simply output the indexes for the search term and return. 如果这时按found == true存活,则found == true您已找到搜索词,您只需输出搜索词的索引并返回即可。

For example, putting it altogether in a short example, you could do: 例如,将其全部放在一个简短的示例中,您可以执行以下操作:

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>   /* for isspace() */

#define STRIDE 5    /* define const for stride */

int main (int argc, char **argv) {

    char puzzle [STRIDE*STRIDE] = {0}, c;   /* puzzle and char */
    size_t psize = STRIDE*STRIDE, n = 0;    /* puzzle size & char count */
    std::string fname = argv[1],            /* filename */
                term = argc > 2 ? argv[2] : "DOG";  /* search term */
    std::ifstream f;    /* file stream */

    if (argc < 2) { /* validate at least filename given as arg */
        std::cerr << "error: insufficien input.\n"
                << "usage: " << argv[0] << "infile\n";
        return 1;
    }

    f.open (argv[1]);   /* open file */
    if (!f.is_open()) { /* validate file open for reading */
        perror (("error file open failed " + fname).c_str());
        return 1;
    }

    while (n < psize && f >> c) /* read file into puzzle */
        if (!isspace (c))
            puzzle[n++] = c;
    f.close();                  /* close file */

    if (n < psize) {    /* validate psize characters read */
        std::cerr << "error: only " << n << "characters read.\n";
        return 1;
    }

    for (size_t i = 0; i < psize; i++) {    /* loop over each char */
        if (puzzle[i] == term[0]) {         /* if matches 1st in term */
            size_t tlen = term.size(),      /* get term size */
                    found = 1;              /* set found flag true */
            if (i + (tlen - 1) * STRIDE >= psize)   /* enough chars left? */
                break;
            for (size_t j = 1; j < tlen; j++)   /* loop 1 to term len */
                if (puzzle[i + j * STRIDE] != term[j]) { /* next !found? */
                    found = 0;      /* set found flag false */
                    break;          /* break loop */
                }
            if (found) {    /* if found, output term & indexes, return */
                std::cout << "found " << term << " at indexes " << i;
                for (size_t j = 1; j < tlen; j++)
                    std::cout << ", " << i + j * STRIDE;
                std::cout << '\n';

                return 0;
            }
        }
    }

    /* only reachable if not found */
    std::cout << "'" << term << "' not found.\n";
    return 1;
}

Example Input File 输入文件示例

$ cat dat/vertword.txt
YRUVG
RTSDC
IFDYU
EPOWE
PWGHT

Example Use/Output 使用/输出示例

$ ./bin/verticalfind dat/vertword.txt
found DOG at indexes 12, 17, 22

$ ./bin/verticalfind dat/vertword.txt RIEP
found RIEP at indexes 5, 10, 15, 20

$ ./bin/verticalfind dat/vertword.txt MOP
'MOP' not found.

Look things over and let me know if you have further questions. 仔细检查一下,如果您还有其他问题,请告诉我。

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

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