Search code examples
c++stringc++17c++20string-view

How to input a std::string_view in C++?


This is the normal way to input(kinda) a std::string_view variable :

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str; // Still have to use std::string class // Resulting in stack/heap allocation
    getline(cin, str);

    string_view view(str);

    return 0;
}

I was wondering is there any way at all to directly input a std::string_view without having to use the string class (using heap allocation) ???

[ I definitely know that a string literal ( like "Hello") is stored directly in the binary code at compile time without causing any stack/heap allocation ... so maybe any way to directly input the string literal into the string_view ??? ]

Note : I want a user input NOT a hard coded string in the code !


Solution

  • No, there is no way to read input into a string view.

    If you want to input a string, you have to store it somewhere. It doesn't necessarily have to be std::string, but that is the simplest option.