迭代每行中的一个字(字符串)C++
问题描述:
所以基本上我想实现的是我有一个文本文件,我必须找到一个特定的单词以及位置(行的位置以及单词所在的位置线)。它如何使用C++基本知识来实现。我是一个新手,也没有研究矢量etc.Thanks对您有所帮助迭代每行中的一个字(字符串)C++
fstream x;
x.open("file.txt);
while(getline(x,str)) {
//extract word from str and save in str1
if(reqWord == str1)
print("match found");
}`
答
这是一种先进的把戏,但我建议你试试stringstream:
std::stringstream ss;
ss << str;
while(ss >> str1)
...
+0
是的,但不幸的是,我的老师不会接受! –
答
你可以为了寻找一个搜索项的特定发生使用find
。它将返回第一次出现的位置,否则npos
(如果它不在当前行上)。 请找一个工作示例如下:
编辑 - 使用与字边界
#include <iostream>
#include <fstream>
#include <regex>
int main() {
std::cout << "Please input the file path" << std::endl;
std::string path;
std::cin >> path;
std::ifstream file(path.c_str());
if (file.is_open()) {
std::string search;
std::cout << "Please input the search term" << std::endl;
std::cin >> search;
std::regex rx("\\b" + search + "\\b");
int line_no = 1;
for (std::string line; std::getline(file, line); ++line_no) {
std::smatch m;
if (std::regex_search(line, m, rx)) {
std::cout << "match 1: " << m.str() << '\n';
std::cout << "Word " << search << " found at line: " << line_no << " position: " << m.position() + 1
<< std::endl;
break;
}
}
} else {
std::cerr << "File could not be opened." << std::endl;
return 1;
}
return 0;
}
您遇到什么麻烦的部分与正则表达式?匹配这个词?确定行号?确定行中的位置?我会逐行读取文本,同时保持读取的行数。使用'string :: find()'检查每一行,并返回字符串开头的位置。 – twain249
找到行中的单词以及行中的位置......以及行位置可以很容易地找出......但找到行中单词的位置 –