2013-08-05 2 views
3

C++을 연습하려면 사용자가 점수를 따라 이름을 입력 할 수있게 한 다음 사용자가 이름을 입력하고 입력 한 점수를 가져올 수있는 간단한 프로그램을 만들려고합니다. 와. 프로그램은 이스케이프 문자 (ctrl + z)를 입력 할 때까지 이름을 입력 한 후 프로그램이 줄을 출력 할 때 이스케이프 문자를 입력 한 후 "점수를 찾는 학생의 이름 입력"을 허용하지만 사용자는 허용하지 않습니다 이름을 입력하고 대신 "아무 키나 눌러 종료하십시오"라고 읽습니다. 나는이 문제를 해결하는 방법에 완전히 곤두 박 쳤고 모든 도움이 크게 감사드립니다. 당신이 cin 스트림에 EOF 상태를 유도하려면 Ctrl + Z 키 조합을 누르면C++ 입력을 허용하기 전에 프로그램이 종료됩니다.

#include "stdafx.h" 
#include <std_lib_facilities.h> 

int main() 
{ 
    vector <string>names; 
    vector <int>scores; 
    string n = " "; // name 
    int s = 0; // score 
    string student = " "; 
    cout << "Enter the name followed by the score. (Ex. John 89)" << endl; 
    while(cin >> n >> s) 
    { 
     for(size_t i = 0; i < names.size(); ++i) 
     { 
      if(n == names[i]) 
      { 
       cout << "Error: Duplicate name, Overwriting" << endl; 
       names.erase(names.begin() + i); 
       scores.erase(scores.begin() + i); 
      } 
     } 
     names.push_back(n); 
     scores.push_back(s); 
    } 
    cout << "Name: Score:" << endl; 
    for(size_t j = 0; j < names.size(); ++j) 
    { 
     cout << names[j]; 
     cout <<" " << scores[j] << endl; 
    } 
    cout << "Enter name of student to look up their score" << endl; 
    cin >> student; 
    for(size_t g = 0; g < names.size(); ++g) 
    { 
     if(student == names[g]) 
     { 
      cout << "Score: " << scores[g] << endl; 
     } 
    } 
    keep_window_open(); 
    return 0; 
} 
+5

eof 플래그를 지우지 않았습니다. – chris

답변

4

, 당신은 다시 사용할 수 있도록 다시 정상 '좋은'상태로 cin 입력 스트림을 가져와야 . for 루프 다음에 벡터의 내용을 인쇄 할 다음 코드를 추가하십시오.

cin.clear(); 

rdstate() 기능을 사용하여 표준 입력 스트림의 상태를 확인할 수도 있습니다. 0 이외의 것은 표준 스트림이 오류 상태임을 의미합니다.

0

앞에서와 같이 레코드를 읽지 못하면 std::cin의 오류 상태를 지워야합니다.

std::cin.clear(); 

트릭을 수행해야합니다. 여기

  • 적절한 데이터 구조 대신에 두 개의 고립 된 벡터
  • CONST 정확성
  • 분리 기능
  • 을 사용하여이 걸릴 내입니다 마법 인덱스
#include <map> 
#include <iostream> 

std::map<std::string, int> read_records() 
{ 
    std::map<std::string, int> records; 

    std::string name; 
    int score; 
    std::cout << "Enter the name followed by the score. (Ex. John 89)" << std::endl; 
    while(std::cin >> name >> score) 
    { 
     if (records.find(name) != end(records)) 
     { 
      std::cout << "Error: Duplicate name, Overwriting" << std::endl; 
     } else 
     { 
      records.insert({name, score}); 
     } 
    } 
    std::cin.clear(); 

    return records; 
} 

int main() 
{ 
    auto const records = read_records(); 

    std::cout << "Name\tScore:" << std::endl; 
    for(auto& r : records) 
     std::cout << r.first << "\t" << r.second << std::endl; 

    std::cout << "Enter name of student to look up their score: " << std::flush; 
    std::string name; 
    if (std::cin >> name) 
    { 
     std::cout << "\nScore: " << records.at(name) << std::endl; 
    } 
} 
  • 더 이상 해키 .erase() 전화

    req 부스트 연속 저장 장치의 경우 flat_map을 사용하십시오.

  • 관련 문제