split string into words and integers

New c++ coder

I would like to accept input "box 3 4 5" or
"triangle 10 10"

and recognize the first as a shape, then do calculations on the remaining numbers but I am having trouble assigning box to a string and the numbers to integers. Some tries result in error "cannot convert std::string to int"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
int main()
{
  istringstream iss;
  string coms;
  getline(cin, coms);
  //cout << "cccccc" << endl;                                                                   
  iss.str (coms);
  //cout << "cccccccc" << endl;                                                                 
  int route = 0;
  string hope;

  int l;
  int w;
  int h;
  int vol;
  int s1;
  int s2;


for(int i = 0; i <=coms.length(); i++)
    {
      string val;
      iss >> val;
      cout << "i = " << i;
      cout << "val = " << val<< endl;
      // cout << "cut one" << endl;                                                             
      string check;
      check = val;
      ///      cout << "check is " << check<< endl;                                             

      if (i=0)
        {
          hope = val;
        }
      if (i=1)
        {
          l = val;
        }
      if (i=2)
	{
          w = val;

          cout << << "length: " << l << "width: " <<  w <<endl;
        }
Last edited on
I've written the raw code to read the values. But it looks like your heading towards writing a factory function that returns a shape read from a stream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
  std::string coms;
  std::getline(std::cin, coms);

  std::istringstream iss(coms);

  // we expect string, then an unspecified number of integers
  std::string shape;
  std::vector<int> params;

  // read them
  iss >> shape;
  int param;
  while (iss >> param)
  {
    params.push_back(param);
  }

  // do something with the values
}
Last edited on
Topic archived. No new replies allowed.