C++ fstream question

I've been a bit confused lately on how to use fstream. I understand the infile and outfile basics, but for example if I were to have a txt file that had questions on it, and say wanted to write a program that allowed a user to see these sets of questions on their screen, and I wanted to allow the user to answer the questions that appeared on their screen, and after being prompted to answer the questions, there answers would appear on the screen side by side each question.

And I've also been confused on how to give for example the text on the txt file, a a string value, and numbers a double value, so that they can stored for later use for calculations for example.

Thanks.
Hints:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <utility>
#include <vector>

void waitForEnter();

int main()
{
    std::ifstream infile("questions.txt");
    std::string line;
    std::vector<std::pair<std::string, std::string>> quest_ans;
    while(std::getline(infile, line)) {
        std::cout << line << ' ';
        int whichq = std::stoi(line);
        std::string answer;
        switch(whichq) {
        case 1:
            std::getline(std::cin, answer);
            break;
        case 2: {
            int probably_false {};
            std::cin >> probably_false;
            std::cin.ignore(1);
            answer = std::to_string(probably_false);
            }
            break;
        case 3: {
            double definitely_false {};
            std::cin >> definitely_false;
            std::cin.ignore(1);
            answer = std::to_string(definitely_false);
            }
            break;
        default:
            break;
        }
        quest_ans.push_back(std::make_pair(line, answer));
    }
    
    infile.close();
    std::ofstream outfile("answers.txt");
    std::cout << '\n';
    for(const auto& v : quest_ans) {
        std::cout << v.first << ' ' << v.second << '\n';
        outfile << v.second << ' ';
    }
    outfile.close();
    std::cout << "You can check 'answers.txt' for your answers.\n";
    
    waitForEnter();
    return 0;
}

void waitForEnter()
{
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}


questions.txt:
1
2
3
1) What's your name [first-name space surname]?
2) How old are you [integer number]?
3) How tall are you in meters [floating point number]? 

Last edited on
Topic archived. No new replies allowed.