【发布时间】:2013-07-29 23:08:23
【问题描述】:
目前,我的任务是将与这些国家/地区包含的所有国家/地区相关的所有国家/地区添加到 mysql 表中...
目前,我打算用 C++ 编写一个程序,它解析两个文件,一个包含国家代码和国家名称,另一个文件包含国家代码和相对于其国家代码的地区。
所以我需要在 mysql 表中添加国家名称和该国家/地区内的地区...
以下是国家代码中的一行 - 国家名称文件:
AD Andorra
这是国家代码 - 地区名称文件中的一行:
ad,aixas,Aix‡s,06,,42.4833333,1.4666667
国家代码-地区名称文件是巨大的!!!所以我首先遍历该文件...在国家代码地区名称文件中的每一行中,我访问另一个文件并将国家代码 - 地区名称文件的前两个字符与国家代码 - 国家名称文件进行比较.我这样做是因为在公司网页中,下拉表应该显示国家名称而不是其缩写。
所以这是我的尝试...
std::vector<std::string> countryRegionArray;
std::vector<std::string> countryCode;
std::string aline;
std::string bline;
std::ifstream myfile ("/Users/settingj/Documents/Country-State Parse/worldcitiespop.txt"); // country code to region
std::ifstream countryCodes ("/Users/settingj/Documents/Country-State Parse/countries.txt"); //country code to country
while (getline (myfile,aline))
{
std::string countryCode; // the country code string
for (int i = 0; i < 2; i++) // loop through the first two characters of the text file to retrieve the Country code
countryCode.push_back(toupper(aline[i])); // push the characters into a vector and convert them to uppercase to compare later
while (getline(countryCodes, bline)) // if the file is readable
{
std::string country; // declare a string variable to store the comparing country code
for (int i = 0; i < 2; i++) // loop through the first two characters of the country code text file
country.push_back(bline[i]); // push the first two characters into the string variable declared in the previous scope
if (countryCode == country) // if string and country code are equal, change countrycode to the last characters of the string in the country-code ->country text file
{
std::string countryName;
for (int i = 4; i < bline.length(); i++)
countryName.push_back(bline[i]);
countryCode = countryName;
}
break;
}
std::string regionName;
int count = 0;
for (int i = 0; i < aline.length(); i++)
{
if (aline[i] == ',')
count++;
if (count == 2) {
regionName.push_back(aline[i+1]);
if (aline[i+2] == ',')
break;
}
}
countryRegionArray.push_back("Country: " + countryCode + " - Region: " + regionName);
}
现在这个 SORTA 可以工作了,我现在真的不担心效率,因为我所做的只是编写一个脚本,而一旦编写了脚本,这个程序可能会被废弃......
这是输出...
Country: Andorra - Region: Aix\340s
Country: AD - Region: Aixirivali
Country: AD - Region: Aixirivall
Country: AD - Region: Aixirvall
如您所见,只有第一行被修改...老实说,为什么会这样...这也不是家庭作业,而是让我公司的网页允许用户注册一个能够从世界上任何国家和地区挑选的设备...
如果有人能看出我做错了什么,请给我一些见解:)...我将不胜感激!!!
或者,如果有人可以将我链接到同时包含国家名称和区域的文件,那将是非常棒的......我只能找到一个国家代码 - 区域文件...... :(
【问题讨论】:
-
C++ 是错误的工具,使用 Python 或 awk 或 Perl 或其他使文本处理变得微不足道的东西
标签: c++ parsing io iostream ifstream