在文件中查找单词
Finding words in a file
此函数构建读取文本输入的树(包含在argv[1]中命名的文件中)。然后,我打开文件,逐字符读取,如果有新行("if(token=='\n')"),请跟踪此行号,并将其存储在向量中,以便稍后访问。接下来,它将其分解为一系列单词(使用除数字或字母符号之外的任何字符作为终止符)。这就是我出错的地方。然后,我尝试将每个字符添加到字符串中,然后当标记是数字或字母符号时,将字符串推到向量中,以便稍后访问。我的逻辑正确吗?当把每个单词推到一个向量中时,你能帮我纠正错误吗。
对不起,如果混淆
BinarySearchTree buildTree (char *argv[]){
ifstream file;
vector<char *> V;
int line = 0;
vector<int> LineNumber;
file.open(argv[1],ios::in);
char token;
string word[] = {};
if (file.is_open()){
token = file.get();//reads the next character from a stream
if (token == 'n')
line++;
LineNumber.push_back(line);
while (token!= ' ' || '0' || '1' || '2' || '3' || '4' || '5' ||'6' || '7' || '8' || '9'){
//while character is not space, digit, or non-alphabetic character
word += token;//adds character to string array *error here
}
V.push_back(word);//adds word to vector *error here
}
}
这一行并没有做你认为它会做的事情:
while (token!= ' ' || '0' || '1' || '2' || '3' || '4' || '5' ||'6' || '7' || '8' || '9')
你必须单独比较,token != '0' && token != '1' ...
。然而,您总是可以利用C标准库(这就是它的用途)
#include <cctype>
while (!std::isspace(token) && !std::isdigit(token))
另外,这里不需要while循环。将其更改为if
。
其次,您正在尝试将char
连接到string[]
。您可能打算声明一个string
。
std::string word = "";
最后,您的vector
是用value_type char*
声明的,但您正试图推回一个字符串。更改为:
std::vector<std::string> V;
以上内容纠正了代码中的即时错误,但可能没有解决核心问题。据我所知,你试图只找到由字母字符组成的字符串(没有数字、空格或标点符号)。你的条件只是变成if (std::isalpha(token))
,因为这排除了其他三个。
其次,代码中没有循环。你只读了一个字符。您可以使用while (std::getline(file, input))
逐行读取文件。由于流的性质,一旦流中没有其他可读取内容,循环就会终止。因此,您的代码变为:
if (file.is_open()){
std::string input;
while (std::getline(file, input))
{
for (std::size_t i = 0; i < input.size(); ++i)
{
token = input[i];
if (token == 'n')
{
line++;
}
LineNumber.push_back(line);
if (std::isalpha(token))
{
word += token;
}
}
V.push_back(word);
word = "";
}
}
注意word = ""
。在构建下一个单词之前,你需要将其留空。
此外,在将单词推入向量之前,您可能需要检查单词是否为空(以避免向量中出现空白条目):
if (word.size()) V.push_back(word);
- 在C++中查找(奇怪的)字符串中的单词
- 从文件中查找单词并替换到其他文件中
- 在文本中查找半个单词"ABBA"的问题
- C++:如何用split查找单词?Regex
- 查找包含指定单词的行(从文件中)
- 创建程序以从给定的.txt文件中查找文本,替换并计算单词
- 如何创建一个函数,该函数在文本中查找单词的匹配项,包括跳过
- 在带有C++的txt文件中查找最长的单词
- 从文件的一行中查找数字的平均值,避免使用第一个单词
- 在文件中查找 10 个最长的单词
- 如何使我的单词查找更清晰、更高效
- 视觉C++查找以 "ing" 结尾且少于或等于 10 个字符的单词
- 如何在没有分隔符的大文本文件中查找所有字典单词
- 我试图编写一个代码来查找一个单词是否是回文,但它不起作用。怎么了?
- 我如何在一串随机生成的字母I C 中查找一个单词
- 在 C++ 的句子中查找某个单词
- Qt使用QWebEngine查找单词功能
- 在向量中通过一个单词查找行
- 单词搜索难题:如何搜索一系列字母来查找单词
- C 查找并替换整个单词