Inputting a dynamic, mutable character array with spaces
Hello :)
This is to anyone who needs the following:
Dynamic array (the size is defined at run-time)
Mutable array (the characters within the array can be edited)
Spaces allowed (the input allows for spaces)
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter the line : ";
string str; //Declare the string
getline(cin,str); //Define the string (getline allows for spaces)
char* characters = NULL; //Make a new character array
int size = str.size()+1; //with str's
characters = new char[size]; //size
characters[size-1] = 0; //terminate with a null
//Copy str's characters into the array called characters
for( size_t copy = 0 ; copy < str.size() ; copy++ )
characters[copy] = str.at(copy);
//You can output the size of the character array
cout << strlen(characters) << endl;
//You can output the actual character array
for( size_t show = 0 ; show < strlen(characters) ; show++ )
cout << characters[show];
cout << endl;
//You can edit the characters
characters[0] = 'Z';
for( size_t show = 0 ; show < strlen(characters) ; show++ )
cout << characters[show];
}
If anyone knows of an easier method, go ahead and post!
Good luck everyone :cool: