string to const string

Oct 21, 2018 at 1:20am
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:33am
Hello Blake7,

I tried this and it appeared to work. I think my compiler is set to C++14 if that makes any difference.

1
2
3
4
5
6
std::string name;

std::cout << "\n Enter name: ";
std::getline(std::cin, name);

const std::string NAME{ name };

For what little bit I did it seems to work.

Hope that helps,

Andy
Oct 21, 2018 at 1:34am
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:49am
Great, thank you guys!
Oct 21, 2018 at 2:54am
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 22, 2018 at 11:49am
@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
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 1:38pm
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 5:03pm
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.
Topic archived. No new replies allowed.