1

So I have a function which edits the values, but I cout the values in main to see that it outputs 1309668848 and changes every time I run the program. (this isn't happening in the preprocessor). I have been struggling with this for a while and decided to come here for advice.

Here's the function.

void GetDahInt() {
    std::string NewValueS;
    getline(std::cin, NewValueS);
    NewValue = (int)NewValueS.c_str();
}

3 Answers3

5

You can use

std::stoi( str )

Discards any whitespace characters (as identified by calling isspace()) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n=base) integer number representation and converts them to an integer value.

Source :Documentation of stoi

XZ6H
  • 1,779
  • 19
  • 25
1

NewValueS.c_str() returns a pointer to array of characters.
You are casting the pointer to int (get the memory address of c_str()).

See: http://www.cplusplus.com/reference/string/string/c_str/

string::c_str Get C string equivalent Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.

NewValue = (int)NewValueS.c_str(); cast the address to string, and the address changes every time you execute your code.

Rotem
  • 30,366
  • 4
  • 32
  • 65
0

You're looking for something like std::stoi (string to int), called like this:

std::string str = ...;
int value = std::stoi(str);

The pros and cons of this option compared to others such as std::stringstream are discussed here: How to parse a string to an int in C++?

The reason your cast produces a "random" number is that c_str returns a pointer to the start of an array of char.

Casting from a const char* to an int is undefined behavior (these types may not even have the same size), but will likely produce a memory address that depends on where your std::string is allocated.

Community
  • 1
  • 1