如何在使用和无发现的情况下使用和不使用的字符串向量搜索元素
how to search an element in a vector of strings using with and without find
我正在尝试通过使用向量来找到一种搜索单词的方法,但是下面的程序没有提供必需的元素
int main(int argc, char *argv[])
{
std::ifstream input_file("test.txt");
std::string line;
std::vector<std::string> elements;
for (int line_no = 1; std::getline(input_file, line); ++line_no)
{
elements.push_back(line);
}
std::vector<std::string>::iterator it = find(elements.begin(), elements.end(), ".");
if (it != elements.end())
std::cout << "element found: " << (*it) << std::endl;
else
std::cout << "element not found " << std::endl;
std::cin.get();
return 0;
}
我尝试了下面没有找到的情况,但是如果失败,否则就会给出类似上述情况的答案
std::vector<std::string>::iterator it = elements.begin();
for (; it != elements.end(); ++it)
{
if ((*it) == ".")
{
std::cout << "element found: " << (*it);
}
else
{
std::cout << "element not found" << std::endl;
}
}
以下是我的输入文件text.txt
中的This is Arif.
I work.
我代码的解决方案是什么,为什么在两种方法中,else else block在块中不给出输出?
您遇到的问题是std::getline
一次读取整行。您的两个示例都在检查整个字符串并将其与"."
进行比较,因此它永远不会匹配。另外,如果您要做的是检查整个行是否包含一个周期(以及在哪里(,则可以使用std::string::find
。
int main(int argc, char *argv[])
{
std::ifstream input_file("test.txt");
std::string line;
std::vector<std::string> elements;
for (int line_no = 1; std::getline(input_file, line); ++line_no)
{
elements.push_back(line);
}
std::vector<std::string>::const_iterator it;
for (it = elements.begin(); it != elements.end(); ++it)
{
std::string temp(*it);
size_t found = temp.find(".");
if (found != std::string::npos)
{
std::cout << "element found at position " << found << std::endl;
}
else
{
std::cout << "element not found " << std::endl;
}
}
std::cin.get();
return 0;
}
相关文章:
- 是否可以在c++中处理字符串流中的各个元素
- 如何将元素添加到向量的字符串位置
- 如何在 Arduino 字符串的开头添加元素.类似于 JS unshift();
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 将包含多个元素的字符串作为输入并转换为矢量 C++
- 如何计算字符串中用户输入元素的出现次数?
- C++ 查找字符串中存在的元素向量
- 如何将凯撒密码的元素从字符串更改为字符串
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- 用字符串 c++ 比较对向量的元素
- 将指针作为缓冲区传递到第一个字符串元素
- C++字符串问题-如何访问字符串元素
- 将字符串集合中的元素添加到字符串集合的向量中
- 如何将字符串加载到BYTE*数组(C++)的元素中
- 需要从字符串数组的一部分访问元素
- 如何打印出常量字符串的第一个元素?
- 如何使用libxml2从C 中的XML文件中检索节点和特定元素字符串而不使用XPATH
- 如何使用XPath使用libxml2从C 中的XML文件中检索节点和特定元素字符串
- 添加元素<字符串、指针>以提升无序哈希图