텍스트 파일의 라인을 변수 myline에 읽어 들인 다음 istringstream을 사용하여이 라인을 토큰 화하려고합니다. 그러나 원래 텍스트 파일 문자열에서 임의의 문자가 손실되는 것으로 보입니다.istringstream을 사용하여 임의의 문자를 잃는 경우
cout<< myline << buff << flush; //print original text file line
istringstream iss(myline);
string sub;
while (iss >> sub) {
cout << "[" << sub << "]" << endl;
}
내 출력을 보면, 당신은 내가 텍스트 파일에서 올바른 문자열을 볼 수 있습니다,하지만 난 istringstream를 사용할 때 다음, (괄호 [] 내에서 볼)의 일부를 개별 토큰을 인쇄 토큰이 조기에 잘 렸습니다.
#include <iostream>
[#include]
[<iostream]
#include <sstream>
[#include]
[<sstream>]
using namespace std;
[using]
[namespace]
[st]
int main()
[int]
[main(]
{
string str(" SOME LONG STRING\twith\nSPACES ");
[string]
[str("]
[SOME]
[LONG]
[STRING\twith\nSPACES]
istringstream iss(str);
[istringstream]
[iss(str);]
string s;
[strin]
while (iss >> s) {
[while]
[(iss]
[>>]
cout << "[" << s << "]" << endl;
[cout]
[<<]
["["]
[<<]
[s]
[<<]
["]"]
[<<]
[e]
}
return 0;
[retur]
}
아무도 내가 잘못하고있는 아이디어가 있습니까? 미리 감사드립니다!
편집 : 다음은 완전히 컴파일 될 코드의 버전입니다. 당신은
#include <cstring>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class MyFileReader {
public:
//constructor
MyFileReader(const char* p);
//destructor
~MyFileReader();
//getLine()
int getLine(char *buffer, int size);
//getCurrentLineNumber()
int getCurrentLineNumber();
void tokenizeLine(vector<string>& vec);
FILE * pFile;
};
//constructor
MyFileReader::MyFileReader(const char* p) {
pFile = fopen(p, "r");
}
//destructor
MyFileReader::~MyFileReader() {
fclose(pFile);
}
//getLine()
int MyFileReader::getLine(char *buffer, int size){
char *out = fgets(buffer, size, pFile);
if (out==NULL) {
return -1;
}
char *pch = strpbrk(out,"\n");
if (pch != NULL) {
return 1;
}
else {
return 0;
}
}
int MyFileReader::getCurrentLineNumber() {
static int mynumber=2;
return mynumber++;
}
//tokenizeLine
void MyFileReader::tokenizeLine(vector<string>& vec) {
string myline("");
char buff[10];
while (1) {
int result = getLine(buff, sizeof(buff));
if (result == -1) {
if (myline.length() > 0)
cout << myline << flush;
break;
}
else if (result == 0) {
myline += buff;
}
else if (result == 1) {
cout<< myline << buff << flush;
istringstream iss(myline);
string sub;
while (iss >> sub) {
cout << "[" << sub << "]" << endl;
}
myline = "";
}
else {
printf("PANIC");
}
}
return;
}
int main(int argc, char **argv) {
vector<string> v;
const char *filename = argv[1];
MyFileReader f(filename);
f.tokenizeLine(v);
return 0;
}
위의 출력을 생성하는 텍스트 파일을 실행할 수 있습니다, 내가 그것을 실행 :
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str(" SOME LONG STRING\twith\nSPACES ");
istringstream iss(str);
string s;
while (iss >> s) {
cout << "[" << s << "]" << endl;
}
return 0;
}
[SSCCE] (http://sscce.org/) + 원래 입력은 좋을 것입니다 – dyp
.. 오류 ... cannot .. 재현 ... 필요 ... 코드의 더 많은 것 ... – dyp
edited 컴파일 가능한 코드 @DyP – user2348283