-2
나는 쉼표를 없애고 secondWord
에 두 번째 단어를 저장하려고 시도한 다음 secondWord
을 출력합니다.두 번째 단어를 추출합니다. 문자열 구문 분석 (C++)
내 코드 :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
istringstream inSS;
string lineString;
string firstWord;
string secondWord;
int i;
bool correct = false;
cout << "Enter input string:" << endl;
while (!correct)
{
// Entire line into lineString
getline(cin, lineString);
// Copies to inSS's string buffer
inSS.clear();
inSS.str(lineString);
// Now process the line
inSS >> firstWord;
// Output parsed values
if (firstWord == "q")
{
cout << "q" << endl;
correct = true;
}
inSS >> secondWord;
if(secondWord[i] != ',')
{
cout<<"Error: No comma in string."<<endl;
}
else if (secondWord[i] == ',')
{
cout << "First word: " << firstWord << endl;
cout << "Second word: " << secondWord << endl;
cout << endl;
}
}
return 0;
}
허용 입력 : 질, 알렌 질, 알렌 질, 알렌
코드는 두 번째 단어와 쉼표를 생산,하지만 난 쉼표와 공백을 없애고 두 번째 단어를 빼내고 싶습니다.
내가 초기화되지 않은 것 같습니다. – lamandy
어쨌든이 질문을 살펴볼 수 있습니다. https://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c 문자열을 토큰 화합니다. – lamandy
초기화되지 않은 경우 코드 동작이 정의되지 않아 아무 일도 발생할 수 없습니다. 어쨌든, 샘플 입력을 제공해야합니다. 'a, b', a, b','a, b'는 코드를 사용하여 매우 다른 결과를 만들어 낼 수 있습니다. – lamandy