C匹配文件中的字符串并获取行号
作者:互联网
我有一个包含前1000个婴儿名字的文件.我想问用户一个名字…搜索文件…然后告诉用户该名字代表男孩名字的等级和女孩名字的等级.如果它不是男孩名或女孩名,它会告诉用户它不在该性别的流行名称中.
该文件的布局如下:
Rank Boy-Names Girl-Names
1 Jacob Emily
2 Michael Emma
.
.
.
输入Michael的所需输出为:
Michael is 2nd most popular among boy names.
如果迈克尔不在女孩名字中,则应说:
Michael is not among the most popular girl names
即使是这样,它也会说:
Micheal is (rank) among girl names
到目前为止,我所拥有的代码如下:我似乎无法弄清楚.谢谢你的帮助.
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
void find_name(string name);
int main(int argc, char **argv)
{
string name;
cout << "Please enter a baby name to search for:\n";
cin >> name;
/*while(!(cin>>name))
{
cout << "Please enter a baby name to search for:\n";
cin >> name;
}*/
find_name(name);
cin.get();
cin.get();
return 0;
}
void find_name(string name)
{
ifstream input;
int line = 0;
string line1 = " ";
int rank;
string boy_name = "";
string girl_name = "";
input.open("/<path>/babynames2004.rtf");
if (!input)
{
cout << "Unable to open file\n";
exit(1);
}
while(input.good())
{
while(getline(input,line1))
{
input >> rank >> boy_name >> girl_name;
if (boy_name == name)
{
cout << name << " is ranked " << rank << " among boy names\n";
}
else
{
cout << name << " is not among the popular boy names\n";
}
if (girl_name == name)
{
cout << name << " is ranked " << rank << " among girl names\n";
}
else
{
cout << name << " is not among the popular girl names\n";
}
}
}
input.close();
}
解决方法:
首先,您似乎正在尝试打开富文本格式文件(.rtf).这将不起作用,因为文件不仅包含文本,还包含其他数据(http://en.wikipedia.org/wiki/Rich_Text_Format).
然后在您的代码中:while(getline(input,line1))每次迭代读取一行.很好,但是在循环中您可以输入>>排名>> boy_name>> girl_name;在下一行继续读取
您想使用line1.您可以从第1行构造一个字符串流,然后从中读取名称:
stringstream ss(line1):
ss >> rank >> boy_name >> girl_name;
那就是贝塔在回答中写的;您会在名称不匹配的每一行中“放弃”.
标签:string-matching,c,iostream 来源: https://codeday.me/bug/20191013/1905253.html