【问题标题】:How to add a string to array in a simple way - C++ [closed]如何以简单的方式将字符串添加到数组 - C++ [关闭]
【发布时间】:2016-05-18 14:44:51
【问题描述】:

所以我有一个老师给我的问题是:将5名员工的姓名和薪水输入两个数组,并打印薪水最高的员工的姓名。

我不确定如何将字符串输入到数组并将其链接到另一个数组,这是我写的:

#include <iostream>
#include <string>
using namespace std;


int main()
{
int salary, x, y;
string name;
int Arr1[5];
int Arr2[5];
x = 0;
y = 0;
for (int i = 0; i <= 5; i++) {
    cin >> Arr1[name];
    cin >> Arr2[x];
    if (x > y) {
        x = y;
    }
}
cout << "Employee" << Arr1[name]<< "has the biggest salary of:" << y << endl;
return 0;
}

【问题讨论】:

  • 也许int Arr1[5]; 应该是string Arr1[5];
  • 您不能使用std::string 索引数组。你真正需要的是std::map&lt;std::string,int&gt;
  • @πάνταῥεῖ - 两个数组工作得很好。尤其是因为这是作业所要求的。
  • @PeteBecker 我知道,我一直在指索引样式。

标签: c++ arrays


【解决方案1】:

我不会为你做你的任务。但我会修复您的错误并帮助您解决问题:

#include <iostream>
#include <string>

int main()
{
   std::string Names[5]; // don't use "namespace std", use std:: instead
   int Salaries[5]; // use proper variable names

   for (int i = 0; i < 5; i++) 
   {
       std::cin >> Names[i] >> Salaries[i];
   }

   /* 
   Breaking down the steps:
   1 - now you have the data, structured and ready
       Names and Salaries // Done
   2 - start from here // Next do this
       find max salary // Search on how to find the max value in an array and save its index
       ....
   3 - find the employee // later
       // use the saved index and get the value from this array
       ....
   4 - display or save or what is required // later, std::cout
   */

   return 0;
}

你需要考虑什么:

Salaries[] 中找到最大值并保存INDEX 您找到的内容,然后转到Names[] 并获取Names[] 中的任何值INDEX .

【讨论】:

  • 我在不使用 std 的情况下修复了它,显然您可以将字符串添加到数组中。显然没有人给我它的简单版本,所以谢谢你的努力。
  • @mar 这很容易。我们为你打破了它。对于每个步骤,请在 Internet 和 StackOverflow 上查找如何执行此操作。您将在不到一个小时内自己完成。你不应该期望有人一次性给你所有的东西。
  • 我一直在搜索,但有些太高级了,注意到这是我第一次编程,所以我不打算在即将到来的决赛中使用非常高级的代码(还在高中)。尽管感谢您将其分解并说清楚!
  • @mar 我添加了更多细节。祝你好运
猜你喜欢
  • 2020-05-30
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 2011-01-03
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
相关资源
最近更新 更多