한 줄을 출력하려고 할 때마다 전체 줄을 가로로 출력하는 대신 파일의 데이터를 세로로 출력합니다. 내 주요 목표는 각 줄을 개별적으로 출력하고 쉼표를 제거하고 CSV 파일에 더 이상 줄이 없을 때까지 반복하는 것입니다.
코드를 실행할 때의 예 :
cout << data[1] << "\t";
산출:
Huggenkizz Pinzz White Dwarf Dildock Operknockity DeVille
내가 얻고 자하는 것은 :
Huggenkizz Amanda 3/18/1997 Sales Associate 2 A A F
내 CSV 파일 :
ID,Last Name,First Name,DOB,DtHire,Title,Level,Region,Status,Gender
1,Huggenkizz,Amanda,3/18/1997,,Sales Associate,2,A,A,F
2,Pinzz,Bobby,5/12/1986,,Sales Associate,3,B,A,F
3,White,Snow,12/23/1995,,Sales Associate,2,C,A,F
4,Dwarf,Grumpy,9/8/1977,,Sales Associate,2,C,A,M
5,Dildock,Dopey,4/1/1992,,Sales Associate,1,B,A,M
6,Operknockity,Michael,10/2/1989,,Sales Associate,1,A,S,M
9,DeVille,Cruella,8/23/1960,,Sales Manager,,,A,F
내 코드 :
vector<string> SplitString(string s, string delimiter)
{
string section;
size_t pos = 0;
vector<string> annualSalesReport;
while ((pos = s.find(delimiter)) != string::npos) //finds string till, if not returns String::npos
{
section = (s.substr(0, pos)); // returns the substring section
annualSalesReport.push_back(section); // places comma split section into the next array
s.erase(0, pos + delimiter.length()); // removes the previous string up to the current pos
}
annualSalesReport.push_back((s));
return annualSalesReport;
}
int main()
{
vector<string> data;
string readLine;
ifstream myIFS;
myIFS.open("SalesAssociateAnnualReport.csv");
int lineCounter = 0;
while (getline(myIFS, readLine))
{
lineCounter++;
if (lineCounter > 1)
{
data = SplitString(readLine, ",");
if (data.size() > 1) //removes top line
{
cout << data[1]<< "\t";
}
}
}
myIFS.close();
return 0;
}
main
다음과 같이 기능을 변경하십시오
int main()
{
vector<vector<string>> data;
string readLine;
ifstream myIFS;
myIFS.open("SalesAssociateAnnualReport.csv");
int lineCounter = 0;
while (getline(myIFS, readLine))
{
lineCounter++;
if (lineCounter > 1)
{
vector<string> dataLine = SplitString(readLine, ",");
data.push_back(dataLine);
}
}
myIFS.close();
// output the first data line of csv file without delimiter and without first column
for (size_t i = 1; i < data[0].size(); i++)
{
cout << data[0][i] << '\t';
}
return 0;
}
원하는 출력을 얻으려면
Huggenkizz Amanda 3/18/1997 Sales Associate 2 A AF
SplitString
기능 을 변경할 필요없이 .
양해하여 주시기 바랍니다 C++
첫 번째 배열 인덱스가 항상 0
대신 1
.
간단한 프로그래밍 모델 IPO 를 따르기 위해 CSV 파일 입력 처리와 출력 생성을 분리했습니다 .
입력-> 프로세스-> 출력
따라서 vector<vector<string>>
원하는 전체 CSV 파일 데이터를 저장하기 위해 문자열 행렬을 도입했습니다 .
주석에서 언급했듯이 SplitString
함수는 리팩터링 될 수 있으며 마지막 두 열을 올바르게 분할하도록 수정해야합니다.
도움이 되었나요?
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다