【问题标题】:Assigning a string to an element of an array?将字符串分配给数组的元素?
【发布时间】:2013-11-26 03:47:39
【问题描述】:

我想编写一个程序,根据加权平均数计算一门课程的最终成绩,并且我正处于提示用户输入每个类别名称的阶段(例如“家庭作业”、“测验”、 ETC)。我将其设置为询问用户他们有多少类别,然后分别询问他们每个类别,然后将每个类别名称作为字符串保存到数组元素中。我知道它可能更容易使用矢量类,但如果可能的话,我想这样做。

#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”的错误。

有人可以帮忙吗?

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    首先,您应该将 categorynames 的类型更改为 string * ,我还注意到 getline 将空格作为第一个值(当 i=0 时),然后将获得正确的输入休息一下,把它改成cin&gt;&gt;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;
            }  
    

    【讨论】:

      【解决方案2】:

      不应该 int * categorynames = new int[categories];std::string *categorynames = new std::string[categories];? 我认为您可以删除text 并使用getline(cin, categorynames[i]);

      【讨论】:

        猜你喜欢
        • 2021-12-12
        • 1970-01-01
        • 2017-06-12
        • 1970-01-01
        • 1970-01-01
        • 2010-10-09
        • 1970-01-01
        • 2016-04-21
        相关资源
        最近更新 更多