string to const string

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?

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
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
Great, thank you guys!
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
@Nwb what do you mean, precisely, by "delete"? How do you "delete" a variable, other than letting it drop out of scope?
Using the delete keyword? I have never seen people using it..
edit: Just read about it.. is it just for pointers?
Last edited on
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
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.