首页 > 解决方案 > 如何使用向量打印文件中的单词列表,每次用户查询 [C++] 一次?

问题描述

目标:当用户输入字母时显示难拼词的 Android/iOS 应用程序。

代码第一次运行正确,但在询问用户是否要输入另一个字母后,文件中的单词列表会显示多次。列表打印的次数是递增的。1,2,3...

预期结果:一个字母的单词列表将打印一次

实际结果:每次程序循环时,单词列表都会打印一次以上。以 i 变量递增。

错误信息:无

试过:

  1. 使用减量修改 printWords()。

    如果 (i == 2){ i--; }

  2. https://www.youtube.com/watch?v=Iho2EdJgusQ

  3. 为什么答案会打印两次?
  4. http://www.cplusplus.com/forum/beginner/199381/
  5. https://codereview.stackexchange.com/questions/139841/printing-out-vectorstring-char-by-char
  6. 将 do-while 更改为 while

代码:

/* 
Description: Android/iOS application that takes in a letter and displays 
tricky-to-spell words.
*/

#include "includeDeclarations.h"
#include "usingDeclarations.h"

char userLetterInput;
char userChoiceContinue;
string userFirstName;
string line;
vector <string> trickyWordsVector;
void printWords();

int main() {
    cout << "----------------<>-----------\n";
    cout << "Welcome to Your TRICKY WORDS Helper!\n";
    cout << "----------------<>-----------\n";
    cout << "\n\nEnter your first name: ";
    cin >> userFirstName;

  do {
    cout << "\nEnter a letter [a - z]: ";
    cin >> userLetterInput;
    userLetterInput = toupper(userLetterInput);

    if(isalpha(userLetterInput)){
        cout << "\n" << userFirstName << ",\n\nHere's your list of tricky words for the letter (" << char(toupper(userLetterInput)) << "):\n" << endl;

    ifstream trickyWordsFile("trickyWordsList.txt");

    if (trickyWordsFile.is_open()) {
        while (getline(trickyWordsFile, line)) {
            if (line.size() > 0) {
                trickyWordsVector.push_back(line);
          }
      }
    } else {
        cerr << "Cannot open the file.";
    }

    trickyWordsFile.close();

    printWords();
    }

    cout << "\nWould you like to enter another letter [y,n]?: "; //TODO data validation
    cin >> userChoiceContinue;
} while(char(tolower(userChoiceContinue)) == 'y');

  cout << "\n----------------<>-----------\n";
  cout << "Thank you for using Your TRICKY WORDS Helper!\n";
  cout << "----------------<>-----------\n";

return 0;
} // end main()

void printWords(){

     //TODO error prints list more than once.
     for (int i = 0; i < trickyWordsVector.size(); i++) {

     if(trickyWordsVector[i][0] == userLetterInput){
     cout << trickyWordsVector[i];
     cout << "\n";
     }
    }
} // end printWords()

usingDeclarations.h

#define cout std::cout
#define cin std::cin
#define getline std::getline
#define endl std::endl
#define string std::string
#define ifstream std::ifstream
#define cerr std::cerr
#define vector std::vector

包括声明.h

#include <iostream>
#include <fstream>
#include <locale>
#include <string>
#include <vector>

rickyWordsList.txt 或rickyWordsFile

Argument 
Atheist 
Axle 
Bellwether 
Broccoli 
Bureau 
Caribbean 
Calendar
Camaraderie 
Desiccate 
Desperate 
Deterrence

感谢您的任何建议。

使用https://repl.it/~运行代码

标签: androidc++iosstringvector

解决方案


只需添加

   trickyWordsVector.clear();

   do

声明它从向量中删除所有元素,因为旧副本始终存在。


推荐阅读