19

i am new to c++. i compiled my code in visual-studio-code in windows10, with 2 variables of type string and string_view. string variable is fine, but string_view is giving errors.I also enable c++17 extension in configuration.json and edit configuration/ui file in vscode.

Here is my code:=

#include<iostream>
#include<string_view>
using namespace std;
int main(){
      string str="hello";
      cout<<str<<endl;
      std::string_view sv=" world";
      auto result=str+sv.data();

      return 0;
}

errors are:=

main.cpp: In function 'int main()':
main.cpp:7:12: error: 'string_view' is not a member of 'std'
       std::string_view sv=" world";
            ^~~~~~~~~~~
main.cpp:7:12: note: 'std::string_view' is only available from C++17 onwards
main.cpp:8:23: error: 'sv' was not declared in this scope
       auto result=str+sv.data();
                       ^~
Abhi38
  • 307
  • 1
  • 2
  • 6

4 Answers4

17

I didn't find any bug in your code. I compiled your code here (Copy your code there and select the language C++17 before compiling) and it is working as expected. Just check the compiler which you are running supports C++17 features. Because std::string_view is only available from C++17 onwards. To enable C++17 in Visual studio check here and in Visual studio code follow this .

Hope this will help you.

Saurav Rai
  • 2,171
  • 1
  • 15
  • 29
2

I'm using gcc compiler for visual studio code. In C++17, gcc has made some changed, including integrating string_view and string together. I think that it seem more complicated now,as string will implicitly convert to string_view, in some case.

For more detail:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0254r2.pdf

2

i solved this error by going to .. project > properties ... select all configurations... > Configuration Properties > C/C++ > Language > C++ Language Standard > ...select ISO C++ 17 Standard(/std::c++17)enter image description here

0

By default, VS sets up the project to x86, but when you open properties, it loads x64 instead. I think VS should load the same settings you are currently using in the IDE, but that's just a personal opinion.

Setting C++17 standard for x86 solved to problem for me. This solution worked for me https://developercommunity.visualstudio.com/content/problem/1133349/namespace-std-has-no-member-string-view.html

Sami
  • 513
  • 4
  • 11