C ++의 파일에서 줄 수를 계산하는 가장 소형 방법
-
22-07-2019 - |
문제
파일의 줄 수를 계산하는 가장 소형 방법은 무엇입니까? 매트릭스 데이터 구조를 작성/초기화하려면이 정보가 필요합니다.
나중에 파일을 다시 살펴보고 정보를 매트릭스 안에 저장해야합니다.
업데이트: Dave Gamble의 기반. 그러나 왜 이것이 컴파일하지 않습니까? 파일은 매우 클 수 있습니다. 그래서 나는 컨테이너를 사용하여 메모리를 저장하지 않으려 고 노력합니다.
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string line;
ifstream myfile (arg_vec[1]);
FILE *f=fopen(myfile,"rb");
int c=0,b;
while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;
fseek(f,0,SEEK_SET);
return 0;
}
해결책
FILE *f=fopen(filename,"rb");
int c=0,b;while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;fseek(f,0,SEEK_SET);
c. 그런 종류의 소형?
다른 팁
나는 이것이 그렇게 할 것이라고 생각한다 ...
std::ifstream file(f);
int n = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n') + 1;
"다시 돌아가야"해야하는 이유가 크기없이 계속할 수 없기 때문에 설정을 다시 주문하십시오.
즉, 파일을 읽고 각 줄을 std::vector<string>
또는 뭔가. 그런 다음 파일의 줄과 함께 크기가 있습니다.
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(void)
{
std::fstream file("main.cpp");
std::vector<std::string> fileData;
// read in each line
std::string dummy;
while (getline(file, dummy))
{
fileData.push_back(dummy);
}
// and size is available, along with the file
// being in memory (faster than hard drive)
size_t fileLines = fileData.size();
std::cout << "Number of lines: " << fileLines << std::endl;
}
컨테이너가없는 솔루션은 다음과 같습니다.
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(void)
{
std::fstream file("main.cpp");
size_t fileLines = 0;
// read in each line
std::string dummy;
while (getline(file, dummy))
{
++fileLines;
}
std::cout << "Number of lines: " << fileLines << std::endl;
}
비록 그것이 가장 효율적인 방법이라고 의심합니다. 이 방법의 이점은 당신이 가면서 라인을 메모리에 저장하는 능력이었습니다.
#include <stdlib.h>
int main(void) { system("wc -l plainfile.txt"); }
인스턴스 수를 계산하십시오 '\n'
. 이것은 *nix ( n) 및 dos/wind 나는 사례가 라인 엔딩으로 단지 r을 생각해내는 것을 본 적이 없으므로 문제가 될 것이라는 것을 알지 못하면 걱정하지 않을 것입니다.
편집 : 입력이 ASCII가 아닌 경우 인코딩 문제도 실행될 수 있습니다. 입력은 어떻게 생겼습니까?
제휴하지 않습니다 StackOverflow