1

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 !

2
  • 1
    Nope. You cannot allow a program to store an arbitrary amount of input data without some additional allocation, and std::string_view does not allocate any additional data by design. Your code is correctly written. Commented Mar 1, 2021 at 3:23
  • 4
    string_view doesn't have its own storage - it's a view onto storage provided by some other object. But the user input needs to be stored somewhere Commented Mar 1, 2021 at 3:23

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.