I am trying to get the first character of a string written to a variable of type char. With std::cin (commented out) it works fine, but with scanf() I get runtime error. It crus
scanf
knows nothing about std::string
. If you want to read into the underlying character array you must write scanf("%s", s.data());
. But do make sure that the string's underlying buffer is large enough by using std::string::resize(number)
!
Generally: don't use scanf
with std::string
.
Another alternative if you want to use scanf
and std::string
int main()
{
char myText[64];
scanf("%s", myText);
std::string newString(myText);
std::cout << newString << '\n';
return 0;
}
Construct the string after reading.
Now for the way directly on the string:
int main()
{
std::string newString;
newString.resize(100); // Or whatever size
scanf("%s", newString.data());
std::cout << newString << '\n';
return 0;
}
Although this will of course only read until the next space. So if you want to read a whole line, you would be better off with:
std::string s;
std::getline(std::cin, s);