문제
또 부탁드려 죄송합니다..지금은 토큰을 하나씩 읽고 있는데 작동하는데 언제 새로운 줄이 나오는지 알고 싶습니다..
내 파일에 다음이 포함되어 있으면
Hey Bob
Now
나한테 줘야지
Hey
Bob
[NEW LINE]
NOW
getline을 사용하지 않고 이를 수행할 수 있는 방법이 있습니까?
해결책
예, 연산자 >> 문자열과 함께 사용하면 '공백'을 읽습니다. '공백'에는 우주 탭과 새로운 라인 문자가 포함됩니다.
한 번에 줄을 읽으려면 std :: getline ()을 사용하십시오.
그런 다음 라인을 문자열 스트림으로 별도로 토큰화할 수 있습니다.
std::string line;
while(std::getline(std::cin,line))
{
// If you then want to tokenize the line use a string stream:
std::stringstream lineStream(line);
std::string token;
while(lineStream >> token)
{
std::cout << "Token(" << token << ")\n";
}
std::cout << "New Line Detected\n";
}
작은 추가 :
getline ()를 사용하지 않고
그래서 당신은 정말로 새로운 라인을 감지 할 수 있기를 원합니다. 이것은 Newline이 다른 유형의 토큰이된다는 것을 의미합니다. 따라서 '흰색 공간'으로 분리 된 단어가 토큰으로, 신성을 자체 토큰으로 분리한다고 가정 해 봅시다.
그런 다음 토큰 유형을 만들 수 있습니다.
그런 다음 토큰에 대한 스트림 연산자를 작성하기 만하면됩니다.
#include <iostream>
#include <fstream>
class Token
{
private:
friend std::ostream& operator<<(std::ostream&,Token const&);
friend std::istream& operator>>(std::istream&,Token&);
std::string value;
};
std::istream& operator>>(std::istream& str,Token& data)
{
// Check to make sure the stream is OK.
if (!str)
{ return str;
}
char x;
// Drop leading space
do
{
x = str.get();
}
while(str && isspace(x) && (x != '\n'));
// If the stream is done. exit now.
if (!str)
{
return str;
}
// We have skipped all white space up to the
// start of the first token. We can now modify data.
data.value ="";
// If the token is a '\n' We are finished.
if (x == '\n')
{ data.value = "\n";
return str;
}
// Otherwise read the next token in.
str.unget();
str >> data.value;
return str;
}
std::ostream& operator<<(std::ostream& str,Token const& data)
{
return str << data.value;
}
int main()
{
std::ifstream f("PLOP");
Token x;
while(f >> x)
{
std::cout << "Token(" << x << ")\n";
}
}
다른 팁
왜 그렇게 생각하는지 모르겠어 std::getline
나쁘다.여전히 개행 문자를 인식할 수 있습니다.
std::string token;
std::ifstream file("file.txt");
while(std::getline(file, token)) {
std::istringstream line(token);
while(line >> token) {
std::cout << "Token :" << token << std::endl;
}
if(file.unget().get() == '\n') {
std::cout << "newline found" << std::endl;
}
}
이것은 내가 현악기 토큰 화를 내기 위해 온 또 다른 시원하고 훨씬 덜 장황한 방법입니다.
vector<string> vec; //we'll put all of the tokens in here
string token;
istringstream iss("put text here");
while ( getline(iss, token, '\n') ) {
vec.push_back(token);
}
제휴하지 않습니다 StackOverflow