如何在 C++ 中将双精度数组中的值"force convert"到字符串输出中?

How to "force convert" a value from an array of doubles into a string output in C++?

本文关键字:convert force 输出 字符串 C++ 数组 双精度      更新时间:2023-10-16

我目前正在研究这个程序。在输入国家名称后,程序将一个国家的粗粮总产量输出为双倍值。我正在使用字符串数组和双精度数组。该程序完美运行和执行:

int main ()
{
string countries[18] = {"World", "Total foreign", "United States", "Canada", "Mexico"};
double grainsProduction[18] = {1361.4, 977.0, 384.4, 26.2, 33.2}
string countryChoice = " ";
int sub = 0;
cout << "Enter country name: ";
getline (cin, countryChoice);
while(sub < 5 && countries[sub] != countryChoice)
{
sub += 1;
}
if (sub < 5)
{
cout << "" << countries[sub] << "'s coarse grain production for 2017/2018 was: " 
<< grainsProduction[sub] << " million metric tons." << endl;
}
else
{
cout << "Invalid country name." << endl;
}    
}

但是,我想在国家/地区数组中包括另一个国家/地区。输入此国家/地区名称时,应输出"未报告"语句。

我想在双精度数组中添加一个虚拟值,如果输入特定国家/地区,它将强制转换为字符串消息"未报告"。如何做到这一点?

也许当您输入国家/地区名称时,您可以使用此代码检查数组中是否有具有该名称的国家/地区,以及是否不显示您的自定义消息。 下面是一个代码示例:

for(int x = 0; x < size; x++){
if (countries[x].find(countryChoice, 0) != std::string::npos){
cout << data[x] << endl;
}
else {
cout << "No data for this Country" << endl;
}