Oct 21, 2018 at 1:20am Oct 21, 2018 at 1:20am UTC
I'm trying to ask the user for their name, but once I have that information how do I convert it into a constant string?
Oct 21, 2018 at 1:34am Oct 21, 2018 at 1:34am UTC
It's not a const string, because you had to have the user enter it after the string was declared.
If you really need a const string, make another variable (Edit: As Handy Andy did) or pass it into a function as a const string.
e.g.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <string>
void func(const std::string& const_string)
{
// can't modify const_string here
}
int main()
{
std::string str;
std::cin >> str;
func(str);
}
Edit:
Furthermore, you could also factor the user entering data into its own function.
Something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
std::string get_input()
{
std::string str;
std::cin >> str;
return str;
}
int main()
{
const std::string str = get_input();
// can't modify str here
}
Last edited on Oct 21, 2018 at 1:38am Oct 21, 2018 at 1:38am UTC
Oct 21, 2018 at 2:54am Oct 21, 2018 at 2:54am UTC
Is using two variables really that necessary instead of simply not using the inputted variable? .-.
By the way would it make sense to delete a variable that was only in temporary use?
Last edited on Oct 21, 2018 at 3:07am Oct 21, 2018 at 3:07am UTC
Oct 22, 2018 at 11:49am Oct 22, 2018 at 11:49am UTC
@Nwb what do you mean, precisely, by "delete"? How do you "delete" a variable, other than letting it drop out of scope?
Oct 22, 2018 at 11:55am Oct 22, 2018 at 11:55am UTC
Using the delete keyword? I have never seen people using it..
edit: Just read about it.. is it just for pointers?
Last edited on Oct 22, 2018 at 11:59am Oct 22, 2018 at 11:59am UTC
Oct 22, 2018 at 1:38pm Oct 22, 2018 at 1:38pm UTC
It's for deleting data on the heap which was allocated by new . The data is accessed through a pointer, yes (Think of it as a handle to the larger data). Modern C++ best practices rarely have the user using new/delete -- use standard library containers instead, like std::string, std::vector, std::map, std::unique_ptr, etc.
Last edited on Oct 22, 2018 at 1:39pm Oct 22, 2018 at 1:39pm UTC
Oct 22, 2018 at 5:03pm Oct 22, 2018 at 5:03pm UTC
Note that delete doesn't actually delete the pointer variable. What it does is frees up the memory that that pointer is pointing to, if that memory was allocated by new (as Ganado says).
The pointer itself will still exist, and will still contain the same value.