C++을 사용하고 있으므로 C 스타일의 코드로 고민하는 대신이 언어가 제공하는 기능을 사용해야합니다. std::vector
을 사용하기로 결정 했으므로 계속해서 문자열 저장에 std::string
, 토큰을 읽을 입력 스트림을 만들기위한 std::istringstream
및 실제로이 토큰을 검색하기 위해 std::getline
을 사용하십시오. 로부터
class elemente
{
public:
std::string name;
// ...
};
다음 검색 토큰 :
처음에는
는,이 클래스의 범위를 외부 elemente
클래스의 속성을 사용할 수 있도록하고 name
std::string
의 유형을 변경하는 액세스 지정public
를 사용 행은 다음과 같을 수 있습니다.
#include <iostream>
#include <vector>
#include <sstream>
...
std::vector<elemente> elements;
std::string line("this is my input line");
std::istringstream lineStream(line);
for (std::string word; std::getline(lineStream, word, ' ');)
{
if (!word.empty())
{
elements.push_back(elemente());
elements.back().name = word;
}
}
그리고이 요소를 테스트하려면 요소 내에 저장된 모든 이름을 인쇄하면됩니다
class elemente
{
public:
elemente(const std::string& s) : name(s){ }
// ...
std::string name;
// ...
};
:
std::vector<elemente>::iterator e;
for(e = elements.begin(); e != elements.end(); ++e)
std::cout << e->name << ".";
출력 :이 벡터의 제대로 초기화 회원들과 당신의 요소를 구성 할 수 있도록
this.is.my.input.line.
은 또한 당신은 당신의 클래스의 public 생성자를 만들 수 있습니다
토큰 구문 분석은 다음과 같이됩니다.
for (std::string word; std::getline(lineStream, word, ' ');)
{
if (!word.empty())
elements.push_back(elemente(word));
}
희망이 도움이 :)
을'strtok'의 결과가 4 개 이상의 문자를 가지고 있기 때문에? –
C가 아닌 C++로 프로그래밍하고 있습니다. 따라서'strcpy'와'strtok' 함수를 제거하고'elemente :: name'의 타입을'std :: string'으로 변경합니다. – LihO
불가능합니다, 다른 것으로 검사했습니다. 변수, 결과는 2 자 길이입니다. – StefanEuSunt