我想编写一个程序,根据加权平均数计算类(class)的最终成绩,我正处于提示用户输入每个类别名称的阶段(例如“家庭作业”、“测验”、 ETC)。我将其设置为询问用户他们有多少个类别,然后分别询问他们每个类别,然后将每个类别名称作为字符串保存到数组元素中。我知道使用 vector 类可能更容易,但如果可能的话,我想这样做。
#include <cmath>
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
cout << "How many grade categories are there for this class? ";
cin >> categories;
int * categorynames = new int[categories];
for (int i(0); i < categories; i++)
{
string text;
cout << "Name of category: ";
getline(cin, text);
categorynames[i] = text;
}
当我编译时,出现“无法在赋值中将 std::string 转换为 int”的错误。
有人可以帮忙吗?
最佳答案
首先,你应该将 categorynames
的类型更改为 string *
,我还注意到 getline
首先给出了一个空格值(当 i=0 时),然后将为其余部分获得正确的输入,因此将其更改为 cin>>categorynames[i]
,如下所示:
string * categorynames = new string[categories];
for (int i = 0; i < categories; i++)
{
//string text;
cout << "Name of category: \n";
cin>>categorynames[i];
//getline(cin, text);
//categorynames[i] = text;
}
关于c++ - 将字符串分配给数组的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20208122/