我这里有2个代码,第一个在这里提示您输入一个数字,然后告诉您文本文件“example.txt”中该行号的内容
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string s;
vector <string> v;
ifstream fileInput;
int qwe = 0;
fileInput.open("example.txt");
while (getline( fileInput, s ))
{
v.push_back( s );
}
cout << "number: " << endl;
cin >> qwe;
cout << "line " << qwe << ": " << v[ qwe ] << endl;
fileInput.close();
}
这里第二个代码提示用户输入然后添加“?”在开始时,因为它是将来我的算法,它将被使用。但随后它会在文本文件中搜索该内容,并向用户提供用户输入内容的行号
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ifstream fileInput;
int offset;
string line;
string search;
cout << "Hi" << endl;
getline(cin, search);
search = "?" + search;
// open file to search
fileInput.open("example.txt");
if(fileInput.is_open())
{
while(getline(fileInput, line))
{
for(unsigned int curLine = 2; getline(fileInput, line); curLine++)
{
if (line.find(search) != string::npos)
{
cout << "found: " << search << " line: " << curLine << endl;
}
}
}
fileInput.close();
}
else cout << "Unable to open file.";
}
所以我的问题是我需要对这些代码进行组合,我需要它以便提示用户输入然后它计算出行号,然后它会在下一行进行couts,我该怎么做?
答案 0 :(得分:0)
像这样做:
#include <fstream>
#include <algorithm>
#include <iostream>
int main()
{
std::string input;
std::cout<<"Enter a line to search for: \n";
std::getline(std::cin, input);
std::fstream File("example.txt", std::ios::in);
if (File.is_open())
{
std::string line;
int line_count = 0;
while(std::getline(File, line))
{
if (line.find(input) != std::string::npos)
{
std::cout<<"The line found was: \""<<line<<"\" at line: "<<line_count<<"\n";
if (std::getline(File, line))
{
std::cout<<"The line after that is: \""<<line<<"\"\n";
++line_count;
}
else
{
std::cout<<"There are no lines after that!\n";
}
}
++line_count;
}
File.close();
}
}
使用以下示例文件:
hello world
I am testing
finding lines
您可以搜索“hello”,它将返回第0行,也就是第一行..
但是,如果您打开find_approximate_line
并搜索“hey world”,由于HammingDistance
算法,它仍会返回第0行。
如果您不关心部分/近距离匹配,那么您可以删除HammingDistance算法并继续使用std::string.find
。
一个示例输出是:
Enter a line to search for:
> hello world
The line found was: "hello world" at line: 0
The line after that is: "I am testing"