[英]C++ file readin with delimiters
名称〜专有名称〜HR编号〜HD编号〜距离-文件中数据的格式
include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string name;
string properName;
string hrN;
string hdN;
double distance;
ifstream fin;
string fileName;
cout << "Enter a file name: ";
getline(cin, fileName);
fin.open(fileName);
if(fin.fail())
{
cout << "Unable to open the file" << endl;
return -1;
}
else
{
string name;
string properName;
string hrN;
string hdN;
double distance;
string line;
string pN1;
bool found = false;
while(true)
{
getline(fin, name, '~');
getline(fin, properName,'~');
getline(fin, hrN,'~');
getline(fin, hdN, '~');
fin >> distance;
cout << "Enter a proper star name:";
string pN1;
cin >> pN1;
if(pN1.compare(properName))
{
found = true;
cout << "Star : "<< "proper name: "<<pN1<< "distance: "<<distance<<"light years" << "HD num: "<<hdN << "HR num: "<< hrN << "common name: "<< name << endl;
}
}
if (found == false)
{
cout << "No star with the properName"<<" "<< pN1 <<" "<<"was found"<< endl;
}
fin.close();
}
return 0;
}
这就是我到目前为止所获得的。 我只是不确定如何存储变量,以便搜索变量并在屏幕上显示特定行的内容
您的代码有很多错误。 由于某种原因,您已经复制了变量名,您的输入循环永不终止,并且您已经询问了有关输入循环内星号的问题。 我想说您在不考虑正在做的事情或不知道要去哪里的情况下急忙进行编码。
让我们一次取一块。
您拥有的第一件事是一堆有关恒星,名称,专有名称,距离等的相关数据。因此,通过将相关数据分组到一个结构中来表达这一事实
struct StarData
{
string name;
string properName;
string hrN;
string hdN;
double distance;
};
现在,让我们编写一个循环以读取该数据,并在没有更多数据时重要地完成
StarData data;
// loop until no more data
while (getline(fin, data.name, '~') && getline(fin, data.properName, '~') &&
getline(fin, data.hrN, '~') && getline(fin, data.hdN, '~') &&
(fin >> data.distance))
{
}
因此,此循环读取恒星数据,一次将一个恒星读入data
变量。 但是到目前为止,该数据还没有做任何事情。
有多种存储数据的方法,以便可以搜索它们,这是很常见的事情,因此C ++会为您完成大部分工作。 我将使用一种称为std::map
东西,它是一种非常擅长存储数据以便可以对其进行搜索的数据结构。 让我们修改上面的循环
#include <map>
std::map<string, StarData> star_database;
StarData data;
// loop until no more data
while (getline(fin, data.name, '~') && getline(fin, data.properName, '~') &&
getline(fin, data.hrN, '~') && getline(fin, data.hdN, '~') &&
(fin >> data.distance))
{
// add star data to database using proper name as the key
star_database[data.properName] = data;
}
此代码将星星数据存储在名为star_database
的变量中。 特别是因为我们使用适当的名称来键入地图,即因为我们说star_database[data.properName] = data;
稍后,我们将能够使用专有名称来查找有关恒星的数据。
现在,我们完成了while循环,让我们询问有关要查找的恒星的问题,并记住这是在上述while循环之后发生的,而不是在其中进行。
cout << "Enter a proper star name:";
string pN1;
cin >> pN1;
现在我们进行查找
auto answer = star_database.find(pN1); // lookup the proper name in the database
if (answer == star_database.end()) // did we find it?
{
cout << "No star with the proper name "<< pN1 <<" was found"<< endl;
}
else
{
cout << "Star : "<< "proper name: "<< pN1 <<
" distance: "<< answer->second.distance << " light years" <<
" HD num: "<< answer->second.hdN <<
" HR num: "<< answer->second.hrN <<
" common name: "<< answer->second.name << endl;
}
我已经跳过了很多细节(我只能解释很多),但希望您有基本的想法,并且可以自己研究其余部分。
所有代码未经测试,对于任何错别字,我们都表示歉意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.