wanna ask about string and converting it into float

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Maria123
    New Member
    • Apr 2015
    • 2

    wanna ask about string and converting it into float

    i need to write a code that accepts string form user like this {1 2 3 ; 1 2 3}
    and then make a function that converts this string into float to put it in an array as a matrix and make operations on it ... could you help me please what to do ?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Are you using C or C++?

    Comment

    • Maria123
      New Member
      • Apr 2015
      • 2

      #3
      i'm using c++ ..........

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Then you should be using a stringstream for this:

        Code:
        string input("{123;456}");
        	stringstream str;
        	char junk;
        	float a;
        	float b;
        
        	str << input;
        
        	str >> junk >> a >> junk >> b >> junk;
        Here you capture your input in a C++ string. Then you insert the string into a stringstream object. These stringstream objects contain a string but operate like a stream (like cin/cout).

        On the input is inserted you extract it using a variable (junk) to hold the {. Then extract the first float. Then use junk again to hold the ;. Then extract the second float. Then use junk again to hold the }.

        Comment

        • RabahMabhoul
          New Member
          • May 2015
          • 6

          #5
          //Input request ! you will get a string in the variable
          getline(cin,var iable);

          //with stod() you can turn a string to a float or double.
          float variable_that_w ill_hold_the_nu merical_value = stod(variable);
          //I hope it helps you!

          Comment

          Working...