2013-06-20 3 views
0

안녕하세요. 저는 C++에 익숙하지 않지만 내 기술은별로 연마되지 않았습니다. 어쨌든 나는 정시에 완료 할 수없는 과제를 가지고 있으며, 실제로 코드를 작동시킬 수 없다는 사실이 나를 괴롭 히고 있습니다. 이제 막 끝내고 싶으므로 앞으로 할 일을 어떻게 알 수 있습니다.C++ 배열로 .txt 파일 열을 읽으십시오.

데이터 파일에는 플레이어 수와 같은 줄에있는 점수가 포함되어 있으며 마지막 열은 시간입니다.

질문입니다. 프로그램에서 열어야하는 .txt 파일이 있습니다 (글 머리 기호없이).

  • 27
  • 팝 23 45 92 34 43 125
  • 경찰 4 23 56 23 75 323
  • ... 등등.

첫 번째 변수를 저장/무시한 다음 데이터 열로 배열을 만들 수있는 방법 (공백으로 구분)?

다음은 내가 작성한 것입니다. 각각의 데이터를 저장해야하는 배열을 만들었습니다.

#include <iostream> 
#include <cmath> 
#include <ctime> 
#include <iomanip> 
#include <vector> 
#include <string> 
#include <sstream> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    cout<<"Welcome to the Score Sorting Program! \n"; 
    cout<<"Please choose a number that corresponds with the way you would like to sort. \n"; 
    cout<<"You may also search by player if you know their username. \n"; 

    string players[50]; //Allocated space for 50 players. 
    int score1[27]; //Array for Score 1 
    int score2[27]; // 
    int score3[27]; // 
    int score4[27]; // 
    int score5[27]; // 
    int time[27]; //Array for Time 
    int i = 0; 
    int j = 0; 

    ifstream myfile; 
    myfile.open("G2347M.txt"); 
    if (!myfile) 
    { 
     cout<<"Could not open file. \n"; 
     system ("Pause"); 
     return -1; 
    } 

    while (!myfile.eof()) 
    { 
     getline(myfile, players[i], ' '); 
     if (i == 26) 
     { 
      i=0; 
      ++j; 
      getline(myfile, players[i],' '); 
     } 
     i++; 
    }  

} 

그래서 기본적으로 플레이어를 점수와 정렬하여 다른 파일로 출력합니다. 나는이 파일을 읽는 첫 부분을 얻고 싶다. 그리고 나는 계속 나아갈 것이다.

비슷한 주제 (4 시간 이상)를 연구하여 코드가 작동하도록했습니다. 내가 할 수있는 모든 것을 연구하고 업데이트 할 것입니다.

+0

벡터와 함께 첫 번째 숫자를 저장하는 것에 대해 여러 스레드가 발견되었지만 배열을 사용해야했습니다. –

+1

플레이어 배열이 정수 배열을 사용하는 이유는 무엇입니까? 그것은 플레이어 이름에 대한 문자열의 배열 것 같습니다. –

+0

죄송합니다. 예, 문자열로 변경했습니다. –

답변

0

다음은 연산자 >>의 캡슐화 및 오버로딩을 사용하는 접근 방식입니다. 저는 여러분이 입력에 대해 설명하고있는 것이 단지 플레이어의 수인 첫 번째 값으로 공간을 구분 한 입력 값의 긴 시퀀스라고 가정합니다.

#include <iostream> 
#include <iomanip> 
#include <string> 
#include <sstream> 
#include <fstream> 
#include <ctype.h> 

using namespace std; 

static const size_t MaxNumPlayers = 50; 

// C++ is about encapsulation, and the player data is 
// discrete yet related, so encapsulate it. 
struct Player 
{ 
    string m_name; 
    int m_scores[5]; 
    size_t GetNumScores() const { return sizeof(m_scores)/sizeof(m_scores[0]); } 
    int m_time; 
}; 

// This allows us to write an operator that will read a player 
// directly from an ifstream. 
std::ifstream& operator>>(ifstream& istr, Player& player) 
{ 
    istr >> player.m_name; 
    for(size_t i = 0; i < player.GetNumScores(); ++i) 
    { 
     istr >> player.m_scores[i]; 
    } 
    istr >> player.m_time; 
    cout << "player: " << player.m_name << ", " << player.m_scores[0] << " @ " << player.m_time << endl; 
    return istr; 
} 

int main(int argc, const char** argv) 
{ 
    ifstream myfile("G2347M.txt"); 
    if (!myfile) 
    { 
     cout<<"Could not open file. \n"; 
     system("Pause"); 
     return -1; 
    } 

    // We can read the number of players directly. 
    size_t numPlayers = 0; 
    myfile >> numPlayers; 
    if (numPlayers <= 0 || numPlayers > MaxNumPlayers) { 
     cout << "Invalid number of players in score file ("<<numPlayers<<")." << endl; 
     system("Pause"); 
     return -1; 
    } 

    Player players[MaxNumPlayers]; 
    size_t playersRead = 0; 

    while (!myfile.eof()) 
    { 
     myfile >> players[playersRead++]; 
     if (playersRead >= numPlayers) 
      break; 
     // drain any spaces after the player. 
     while(isspace(myfile.peek())) 
      myfile.ignore(); 
    } 

    if (playersRead != numPlayers) 
    { 
     cout << "Problem reading score file, expected " << numPlayers << " but read " << playersRead << endl; 
     system("Pause"); 
     return -1; 
    } 

    cout<<"Welcome to the Score Sorting Program! I read "<<playersRead<<" players."<<endl; 
    cout<<"Please choose a number that corresponds with the way you would like to sort."<<endl; 
    cout<<"You may also search by player if you know their username.\n"<<endl; 

    /* ... */ 

    system("Pause"); 
    return 0; 
} 
+0

맨 위에 MaxNumPlayers를 선언 할 때 size_t의 사용법을 설명 할 수 있습니까? 나는 정확히 거기에 무슨 일이 일어나고 있는지에 대해 조금 혼란 스럽지만,이 함수는'if (numPlayers <= 0 || numPlayers> MaxNumPlayers) {...}' – andrewec

+0

' size_t '는 크기 값을 보유하기위한 상대적으로 표준적인 유형입니다. 'static const size_t NumPlayers = 5;'는 지역적으로 범위가 지정된 상수입니다. 즉, 어디서나 '5'를 사용하는 대신 의미있는 이름의 값을 만들었습니다. 'int x = 32 + 5;'또는'int x = 37;이 보이면 그 숫자의 의미를 어떻게 알 수 있습니까? 'int x = FirstPlayerNum + NumPlayers'는 그 자체를 설명합니다. – kfsone

+0

그건 의미가 있습니다 -하지만 왜 그냥'static const NumPlayers = 5'를 사용하지 않을까요? 나는 그것이 내가 끊어 버린 곳이라고 생각한다. – andrewec

0

왜 50 명의 선수가 27 점입니까?

첫 번째 줄은 읽으려는 총 줄 수라고 가정합니다. 그렇다면 배열을 동적으로 할당하여 50 개 (또는 27 개) 행을 처리하는 대신 모든 데이터를 보유 할 수 있습니다. 하나의 라인에 대한 모든 데이터를 여러 개의 연결되지 않은 배열에 분산시키는 대신 구조체에 결합 할 수도 있습니다.

의사 코드 :

int lineNo = 1; 
int totalLines = -1; /* not set */ 

while(line = read_a_line()) { 
    if (lineNo == 1) { 
     totalLines = convert_line_text_to_number(); 
    } 
    else { 
     /* split the line into "tokens" separated by white space */ 
     /* store each token in the correct array */ 
    } 
    lineNo++; 
    /* if lineNo is too big, break the loop */ 
} 
+0

그것은 27 줄이지만 지침은 최대 50 명의 플레이어를위한 공간을 할당한다고 말한다. 파일에 27이 있습니다. –

0

이 벡터의 사용됩니다 사용하는 가장 좋은 방법. 그러나 당신이 말했듯이 배열을 사용하도록 바인딩되어 있으므로 여기에 코드가 있습니다.

#include <iostream> 
#include <fstream> 
#include <sstream> 

using namespace std; 

int main() 
{ 
    ifstream file; 
    file.open("sample.txt"); 

    string name[50]; 
    int score1[27],score2[27],score3[27],score4[27],score5[27],time[27]; 


    int i = 0; 
    while(!file.eof()) 
    { 
     string line; 
     getline(file,line); 
     char* a = const_cast<char*>(line.c_str()); 
     char* pch = strtok (a," "); 

     name[i] = pch; 
     int counter = 1; 
     while (counter < 7) 
     { 
      pch = strtok (NULL, " "); 

      if(counter == 1) 
      { 
       score1[i] = atoi(pch); 
      } 
      else if(counter == 2) 
      { 
       score2[i] = atoi(pch); 
      } 
      else if(counter == 3) 
      { 
       score3[i] = atoi(pch); 
      } 
      else if(counter == 4) 
      { 
       score4[i] = atoi(pch); 
      } 
      else if(counter == 5) 
      { 
       score5[i] = atoi(pch); 
      } 
      else if(counter == 6) 
      { 
       time[i] = atoi(pch); 
      } 

      ++counter; 
     } 

     ++i; 
    } 

    //cout<<a; 
    return 0; 
} 

문제가 있으면 알려 주시기 바랍니다. 나는 파일과 같은 몇 가지 기본적인 상식 검사를 추가하지 않았다. 당신의 버전에서 그렇게하라.

관련 문제