2014-04-04 3 views
0

이것은 내 CS1337 클래스 용이므로 주 기능 내에서 작업해야합니다. if/else 및 switch 문을 사용하여 루프 만 사용할 수는 없습니다.학생을위한 파일 사용 up-class 숙제

메모장에 읽을 이름 목록이 있어야하는 Lines.txt 파일을 만들었습니다. 최종 결과는 모든 이름을 읽고 콘솔 출력에 메시지를 표시해야합니다. 어떤 도움을 크게 감상 할 수 Question about my design for my C++ homework

:

나는 내가 온라인 여기 이전 항목 떨어져 내 코드를 기반으로.

Lines.txt

Leslie 
Ron 
Tom 
Gerry 
Donna 
Andy 
April 
Chris 
Ben 
Mark 

콘솔 창 출력 :

Andy should be at the head of the line. 
Tom should be at the end of the line. 

내 코드 :

int main() 
{ 
    ifstream inputFile; 
    string filename; 

    string front, back, student; 
    int students = 10; 

    // Get the filename from the user. 
    cout << "Enter the filename: "; 
    cin >> filename; 

    // Open the file. 
    inputFile.open(filename.c_str()); 

    // If the file successfully opened, process it. 
    if (inputFile) 
    { 
/* A formula the sets each name entered to 
the variables front and back*/ 

    front = back = student; 

    // Read the numbers from the file and 
    // display them. 

    while (inputFile >> student) 
    { 
    for (int count = 1; count <= students; ++count) 
    { 
     // Create an if/else statement that decides which 
     // student name is alphabetically first and last 

    if (student < front) 
     front = student; 
    else if (student >= back) 
     back = student; 
    } 
    // Display the message showing which name is alphabetically first and last name 
    } 
    cout << endl 
     << front << " should be at the head of the line." << endl 
      << back << " should be at the end of the line." << endl; 
    // Close the file. 
    inputFile.close(); 
} 
    else 
{ 
    // Display an error message. 
    cout << "Error opening the file.\n"; 
} 
return 0; 
} 
+0

이 질문은 codereview.stackexchange.com에 – AShelly

+0

AShelly의 권리를 속하기 때문에 오프 주제로 표시 그렇지 않으면 코드 검토가 퇴색합니다. –

답변

1

나쁜 시작. 가장 큰 문제는 이것이다 :

if (student < front) 

이 실행 처음, front가 빈 문자열 ... 아무것도 빈 문자열 이하로 비교하는 것입니다. 아마도 가장 쉬운 수정은 다음과 같습니다

if (count == 1) 
    front = back = student; 
else if (student < front) 
    ...etc... 

마이너 nitpicks :

  • 첫 번째 front = back = student; 않습니다 아무것도 ... 모든 문자열은 기본적으로 구성 어쨌든 비어 있습니다.

  • 봅니다 만들고 ... 예를 들어, 가능한 한 늦게로 if (std::ifstream inputFile(filename) { ... } else { ...couldn't open... } 당신의 변수를 초기화하기 - std::ifstream가 소멸자에서 파일을 닫습니다 어떠한 .close() 호출이 필요하지 않습니다. C++ 11 이전에는 .c_str() 만 필요합니다. 당신이 작동하지 않는 말을 명확하게해야하고 무엇을 출력하면 점점 그렇게 사람들을위한 특정 질문에있다 -

+0

좋아, 나는 앞 문자열에 대한 값을 초기화하여 뒷 문자열과 자체 비교할 수 있어야한다. 문제는 루프에 if/else 문을 입력하면됩니다. 나는 이제 앞뒤 모두 콘솔 윈도우 출력 "Mark"를 갖게되었다. 나는 방정식 = 백 = 학생을 입력하는 것을 시도했다; 루프가 시작되기 전에 while 루프 내에서 여전히 동일한 출력을 얻습니다. – user3496053

+0

Mark는 입력의 마지막 줄입니다. count = 1 일 때도 front = back = student로 설정하고 있음을 나타냅니다. "if"조건을 내 대답에 넣었는지 확인하고, 여전히 답을 쓸 수 없다면 문제를 찾아 귀하의 현재 코드를 귀하의 질문에 편집하십시오. 그래서 당신이 무엇을하고 있는지 알 수 있습니다. 환호 –

+0

나는 그것을 이해했다. 내가 그것을 비교하기 위해 이름의 입력을 계속 받아들이는 것이 필요했다. inputFile >> 학생; 이 for 루프 안에 배치해야했습니다. – user3496053