how to cast a vector to an int

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manontheedge
    New Member
    • Oct 2006
    • 175

    how to cast a vector to an int

    is it possible to cast a vector of strings to an integer?

    I tried ...


    Code:
    	vector<string> data;
    	string values;
    	ifstream in("pf.ppm");
    	ofstream out( "pf_sin.ppm");
    
    
    	while( in.good() )
    	{
    		in >> values;
    		data.push_back(values);
    	}
    
    	int row = (int)data[6];
    	int column = (int)data[7];

    the values in data are filled with values ... when I try this I get conversion errors when compiling. I've never tried to cast a vector, so, is it possible? if so, how can I do it? I appreciate any help.
  • Man4ish
    New Member
    • Mar 2008
    • 151

    #2
    Here you are casting the type of element of vector (string) to int . Treat it like simple conversion from string to int .By uisng atoi() function you can convert the string to int.

    Regards
    Manish

    Comment

    • oler1s
      Recognized Expert Contributor
      • Aug 2007
      • 671

      #3
      is it possible to cast a vector of strings to an integer?
      Technically yes, but it’s not a meaningful cast. Casting does not mean converting. Also, since this is C++, you’ll want to learn about using the C++ casts as opposed to the C cast. It’s not an optional topic to learn.

      In any case, what you are really asking is how to convert a string to an integer. You’ll want to look up stringstreams for this. Use a stringstream to attempt to convert each string into an integer.

      Comment

      • oler1s
        Recognized Expert Contributor
        • Aug 2007
        • 671

        #4
        Also, your look to read in value is problematic. First you have in >> values. Then you push back the value. Now, what you want is that you read in values until you run out of values. And the idea is that in.good() returns false. But wait. Look at in >> values. It attempts to read from the file. Are you guaranteed success? Could in >> values possibly fail? Could at that very moment, there be no value to read? If you say yes, then what do you do immediately afterwards?

        Comment

        Working...