Programing

왜 문자열을 부를 수 없습니까?

crosscheck 2020. 7. 2. 07:54
반응형

왜 문자열을 부를 수 없습니까?


내가 cout string이것을 좋아할 수없는 이유 :

string text ;
text = WordList[i].substr(0,20) ;
cout << "String is  : " << text << endl ;

이 작업을 수행하면 다음 오류가 발생합니다.

오류 2 오류 C2679 : 이진 '<<': 'std :: string'유형의 오른쪽 피연산자가 필요한 연산자를 찾을 수 없습니다 (또는 변환이 허용되지 않음) c : \ users \ mollasadra \ documents \ visual studio 2008 \ 프로젝트 \ barnamec \ barnamec \ barnamec.cpp 67 barnamec **

이것조차도 작동하지 않는다는 것은 놀라운 일입니다.

string text ;
text = "hello"  ;
cout << "String is  : " << text << endl ;

당신은 포함해야합니다

#include <string>
#include <iostream>

std어떻게 든 cout의 네임 스페이스를 참조해야합니다 . 예를 들어

using std::cout;
using std::endl;

함수 정의 또는 파일 위에


코드에는 몇 가지 문제가 있습니다.

  1. WordList어디에도 정의되어 있지 않습니다. 사용하기 전에 정의해야합니다.
  2. 이런 함수 외부에서 코드를 작성할 수는 없습니다. 함수에 넣어야합니다.
  3. 당신은 필요 #include <string>당신이 사용하기 전에 문자열 클래스와 iostream을 사용하기 전에 coutendl.
  4. string, coutendl에 살고있는 std당신이 그들을 접두사없이 액세스 할 수 있도록, 네임 스페이스 std::는 사용하지 않는 using최초의 범위로 가져에 지시합니다.

위의 답변은 좋지만 문자열 포함을 추가하지 않으려면 다음을 사용할 수 있습니다

ostream& operator<<(ostream& os, string& msg)
{
os<<msg.c_str();

return os;
}

참조 std::cout하거나 std::endl명시 적으로 언급 할 필요는 없습니다 .
둘 다에 포함되어 있습니다 namespace std. 매번 using namespace std스코프 해상도 연산자를 사용하는 대신 ::쉽고 편리합니다.

#include<iostream>
#include<string>
using namespace std;

리눅스 시스템을 사용하는 경우 추가해야합니다

using namespace std;

헤더 아래

윈도우가 그렇다면 헤더를 올바르게 넣으십시오. #include<iostream.h>

#include<string.h>

이것이 완벽하게 작동한다는 것을 참조하십시오.

#include <iostream>
#include <string>

int main ()
{
std::string str="We think in generalities, but we live in details.";
                                       // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

   std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     
// get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

참고URL : https://stackoverflow.com/questions/6320995/why-i-cannot-cout-a-string

반응형