2016-12-31 3 views
0

질문과 4 개의 대답을 표시하는 코드를 작성하고 올바른 것을 선택하고 선택 사항을 확인하십시오. 이제는 6 개의 열을 포함하는 테이블을 만들 것입니다 : 질문/a/b/c/d/correct_answer 및 내 질문에 약 100 줄. 이제 내 프로그램을 에 무작위로 5의 질문을 테이블에 표시하고 사용자에게 표시하고 싶습니다.테이블에서 C++ 퀴즈 응용 프로그램 데이터

첫 번째 질문은입니다. Excel에서 내 테이블을 만들고 Visual Studio에서 사용할 수 있습니까? 그렇지 않다면 가능한 한 간단하게 테이블을 만들기 위해 어떤 소프트웨어를 사용해야하며 Visual Studio 프로젝트에이를 구현하는 방법은 무엇입니까? 그렇다면 Visual Studio 프로젝트에 Excel 테이블을 구현하는 방법은 무엇입니까?

두 번째 질문은 내 테이블에서 100 개 질문 중 5 개를 무작위로 선택하려면 가장 간단한 코드를 써야합니까?

질문의 코드는 다음과 같습니다

int main() 
{ 

    string ans; //Users input 
    string cans; //Correct answer, comes from table 
    string quest; //Question, comes from table 
    string a; // Answers, come from table 
    string b; 
    string c; 
    string d; 
    int points; //Amount of points 

    points = 0; 

    cout << "\n" << quest << "\n" << a << "\n" << b << "\n" << c << "\n" << d << "\n"; 
    cout << "Your answer is: "; 
    cin >> ans; 
    if (ans == cans) 
    { 
     points = points + 1; 
     cout << "Yes, it is correct\n"; 
    } 
    else 
    { 
     cout << "No, correct answer is " << cans << "\n"; 
    } 


    return 0; 
} 
+0

쉬운처럼 데이터를 것 : 여기

#include <cstdlib> // for srand() and rand() #include <ctime> // for time() . . . srand(time(NULL)); // seed the RNG on seconds . . . var = rand() % ONE_MORE_THAN_MAX; 

나 자신이 시험 공부에 도움이 만든 quizzer입니다 질문 당 줄, 당신은 임의의 레코드를 가져올 필요가 있다면 숫자로 색인 생성을 지원하는 데이터 구조를 사용해야합니다 도움이 되었습니까 –

답변

0

첫 번째 부분

당신은 당신의 질문을 편집하고 저장 Excel을 사용하여 확실히 할 수 있습니다. 그러나 파일을 저장할 때 파일 형식에주의하십시오.

Excel 파일을 .xls 또는 .xlsx 파일 대신 .csv 파일로 저장하려고합니다. 파일 -> 다른 이름으로 파일 저장 ->으로 이동하여 유형을 .csv으로 변경하십시오.

.csv 파일을 읽는 것이 훨씬 쉽기 때문입니다. .csv 파일은 각 셀을 쉼표 (,)로 구분하고 각 행을 줄 바꿈 ('\n') 문자로 구분합니다.

그래서, 여기에 샘플 엑셀 파일입니다

Sample Data in Excel format

가 나는 .csv 파일로 저장하고 (여기, 아톰) 텍스트 편집기를 사용하여 파일을 연 후에는, 그것은 다음과 같습니다

Sample Data in .csv format

그런 다음 파일을 읽는 데 필요한 코드를 작성해야합니다.

이것은 내가 사용되는 코드 (나는 초보자를위한 코드를 더 명확하게 과도한 주석을 추가 한)입니다 :

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

using namespace std; 
const int MAX_QUESTIONS = 3; 
const int COLUMNS = 6; //Question, Options A, B, C, D, Correct Answer 

int main() { 

    ifstream fp; 
    fp.open("test.csv"); 

    //If file could not be opened 
    if (fp.fail()) { 
     std::cout << "failed to open file" << std::endl; 
     return 1; 
    } 

    //Create a 2D vector of strings to store the values in the file 
    vector< vector<string> > table; 

    string line; 

    //Loop through the entire file (fp) 
    //Store all values found until I hit a newline character ('\n') in the string line 
    //This loop automatically exits when the end-of-file is encountered 
    while (getline(fp, line, '\n')) { 

     //Create an temporary vector of strings to simulate a row in the excel file 
     vector<string> row; 

     //Now I am passing in this string into a string stream to further parse it 
     stringstream ss; 
     ss << line; 

     string part; 

     //Similar to the outer loop, I am storing each value until I hit a comma into the string part 
     while (getline(ss, part, ',')) { 

      //Add this to the row 
      row.push_back(part); 
     } 

     //Add this row to the table 
     table.push_back(row); 
    } 

    //Print out the entire table to make sure your values are right 
    for (int i = 0; i <= MAX_QUESTIONS; ++i) { 
     for (int j = 0; j < COLUMNS; ++j) { 
      cout << table[i][j] << " "; 
     } 
     cout << endl; 
    } 

    return 0; 
} 

두 번째 부분

은 임의의 숫자를 선택하려면, 당신은이를 사용할 수 있습니다 코드 old method 달리

#include <random> 

std::random_device rd;  // only used once to initialise (seed) engine 
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case) 
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased 

auto random_integer = uni(rng); 

(나는 another answer로부터 차용)이 하단쪽으로 바이어스를 생성하지 않는다. 그러나 새로운 엔진은 C++ 11 컴파일러에서만 사용할 수 있습니다. 그래서 그걸 명심하십시오. 이전 방법을 사용해야하는 경우 다음을 따라 편차를 수정할 수 있습니다 answer.

5 개의 다른 숫자를 선택하려면 임의의 숫자를 생성 할 때마다 배열에 저장하고이 숫자가 이미 사용되었는지 확인하십시오. 이것은 질문의 반복을 막을 수 있습니다.

+0

네, 답장을 보내 주셔서 감사합니다. 나는 당신의 계단을 따랐고 나의 프로그램은 나의 테이블을 잘 프린트했다. – Mac

+0

하지만 처음에 해제 된 내 문자열에 모든 줄 (질문, 대답 a, 대답 b 등)의 부분을 연결하는 방법은 무엇입니까? – Mac

+0

글쎄, 내가 해결책을 찾은 것 같아,하지만 당신은 비교 게시 할 수 있습니다. – Mac

0

질문 1로 대답하려면 : Excel에서 파일> 다른 이름으로 저장을 클릭하십시오. UTF-16 유니 코드 텍스트 (.txt)를 선택하고 파일의 이름을 지정하고 프로그램에서 액세스 할 수있는 곳에 저장합니다. 같은 디렉토리에있는 텍스트 파일로

#include <fstream> 

질문이 대답하기

ifstream fin; 
fin.open("FILENAME.txt"); 
. 
. 
. 
fin >> variable; 
. 
. 
. 
fin.close(); 

를 사용하십시오 : 당신의 C++ 프로그램에서 텍스트 파일에 대한 fstream 라이브러리를 사용하십시오 랜드() 함수가 그 0과 RAND_MAX 사이의 정수를 반환합니다. 그런 다음 모듈러스 (%)를 사용하여 원하는 범위의 난수를 얻을 수 있습니다. 하나

#include <iostream> 
#include <fstream> 
#include <cstdlib> 
#include <cstring> 
#include <ctime> 
using namespace std; 

const char QUESTIONS_FILE_NAME[] = "questions.dat"; 
const char QUESTION_ANSWER_SEPARATOR = ','; 
const char QUESTION_SEPARATOR = '\n'; 

const short MAX_QUESTION_LENGTH = 300; 
const short MAX_ANSWER_LENGTH = 300; 
const short MAX_NUM_QUESTIONS = 300; 


int main() 
{ 
    char questions[MAX_NUM_QUESTIONS][MAX_QUESTION_LENGTH]; 
    char answers[MAX_NUM_QUESTIONS][MAX_ANSWER_LENGTH]; 
    short counter = 0; 

    short question_choice; 

    char user_answer[MAX_ANSWER_LENGTH]; 

    ifstream fin; 
    fin.open(QUESTIONS_FILE_NAME); 


    srand(time(NULL)); 


    while(fin.getline(questions[counter], MAX_QUESTION_LENGTH-1, 
    QUESTION_ANSWER_SEPARATOR)) 
    { 
    fin.getline(answers[counter], MAX_ANSWER_LENGTH-1, 
     QUESTION_SEPARATOR); 
    counter++; 
    } 

    fin.close(); 

    cout << endl << "Press CTRL+C to quit at any time" << endl << endl; 

    while (counter > 0) 
    { 
    question_choice = rand() % counter; 

    cout << endl << questions[question_choice] << " "; 
    cin >> user_answer; 

    if (strcmp(user_answer, answers[question_choice])) 
    { 
     cout << endl << "Incorrect" << endl 
     << "It was " << answers[question_choice] << endl; 
     strcpy(questions[counter], questions[question_choice]); 
     strcpy(answers[counter], answers[question_choice]); 
     counter++; 
    } 
    else 
    { 
     cout << endl << "Correct" << endl; 
     counter--; 
     strcpy(questions[question_choice], questions[counter]); 
     strcpy(answers[question_choice], answers[counter]); 
    } 
    } 


    cout << endl << "You Win!!!!" << endl; 

    return 0; 
} 

questions.dat 텍스트 파일에서 데이터를로드하는 것이

In what year was the Pendleton Civil Service Reform Act enacted? 
a.1873 
b.1883 
c.1893 
d.1903,b 
In what year did Hurricane Katrina occur? 
a.2001 
b.2003 
c.2005 
d.2007,c 
+0

rand() 함수는 하단에 바이어스를 생성합니다. 그리고 이것은 (1,100)만큼 작은 범위를 다룰 때 매우 잘 보입니다. C++ 11 컴파일러를 사용하지 않는 한 [here] (http://stackoverflow.com/a/19728404/5055644) 방법을 사용할 수 있습니다. 왜'char's 대신'string's를 사용합니까? 당신은 문자열의 길이에 대해 걱정할 필요가 없습니다 (또는 나는 그것을 가정하는데 잘못입니까?) – Apara