매우 유사한 사례에 대한 유사한 게시물을 많이 보았지만 내 사례는 약간 다릅니다. 저는 C ++의 초보자이므로 어떤 도움을 주시면 감사하겠습니다.
정수로 가득 찬 줄로 가득 찬 큰 파일이 있습니다. 각 숫자는 공백으로 구분됩니다. 별도의 줄이 필요합니다. 한 번에 모든 파일을 읽고 싶지 않습니다. 한 줄씩 읽고 각 줄을 정수 벡터로 구문 분석하고 싶습니다. 내가 가진 코드는 다음과 같습니다.
int main () {
string line;
ifstream myfile;
myfile.open ("numbers.txt");
vector<int> vec1;
int const2=0;
int a;
while ( getline (myfile,line) ){ // I understand that this reads line
// by line and stores the string to "line"
while (line >> a){ // this part is the one i can't get right, i
// want to push_back every int from
// the string to vec1 but doesn't work
vec1.push_back(a);
// More stuff
}
// more stuff
}
myfile.close();
return 0;
}
다음은 C ++ 11 방식 ( -std=c++0x
g ++ 또는 clang ++과 함께 사용 )입니다. 모르는 각 기능을 Google에서 검색 할 수 있습니다. back_inserter
and를 사용하면 istream_iterator
while / for 루프보다 훨씬 깨끗합니다. deque
이 컨텍스트에서 사용 하는 것도 더 효율적입니다. 물론 기본 입력에서 파일 이름을 가져올 수도 있습니다.
#include <algorithm>
#include <iterator>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <deque>
int main()
{
const std::string filename = "/path/to/file.txt";
std::string line_buf;
std::ifstream file( filename );
std::deque< std::deque<int> > parsed_data;
if (file) while ( std::getline(file,line_buf) )
{
std::deque<int> parsed_line;
std::stringstream ss( line_buf );
std::copy( std::istream_iterator<int>(ss), std::istream_iterator<int>(), std::back_inserter(parsed_line) );
parsed_data.emplace_back();
parsed_data.back().swap( parsed_line );
}
}
콘솔에서 결과를 확인하려면이 기능을 사용할 수 있습니다.
#include <cstdio>
void show_result( const std::deque< std::deque<int> >& data )
{
size_t line_count = 0;
for ( auto& line: data )
{
printf( "Line %02ld: ", ++line_count );
for ( auto& num: line )
printf( "%d ", num );
printf( "\n" );
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다