how to put a string into an integer array c++

前端 未结 4 807
抹茶落季
抹茶落季 2021-01-03 14:27

I have a string that contains what ever the user has input

string userstr = \"\";
cout << \"Please enter a string \";
getline (cin, userstr);
<         


        
相关标签:
4条回答
  • 2021-01-03 14:51

    You can access each element in your string using the [] operator, which will return a reference to a char. You can then deduct the int value for char '0' and you will get the correct int representation.

    for(int i=0;i<userstr.length();i++){
        myarray[i] = userstr[i] - '0';
    }
    
    0 讨论(0)
  • 2021-01-03 15:00

    Here is one way to do it

    for(int i=0;i<userstr.length();i++){
        myarray[i] = userstr[i];
    }
    
    0 讨论(0)
  • 2021-01-03 15:04

    You can just simply use isstringstream to convert the string to int as follows

    istringstream istringName(intString);
    istringName >> real_int_val;
    

    now it has magically become a int containing all numbers from string However I do not see why you would not cin it as a int in the first place??

    0 讨论(0)
  • 2021-01-03 15:09
    int* myarray = new int[ userstr.size() ];
    
    std::copy( usestr.begin(), userstr.end(), myarray ); 
    

    The terminating zero was not appended to the array. If you need it you should allocate the array having one more element and place the terminating zero yourself.

    0 讨论(0)
提交回复
热议问题