Please help, fstream/stringstream

closed account (GwXSz8AR)
figured it out, thank you everyone.
Last edited on
Please post the code showing what you tried.

Also please post a sample input file, so that we are all working with the same data.


closed account (GwXSz8AR)
thank you, solved.
Last edited on
To me part of your instructions don't make a lot of sense. Part of the purpose of stringstreams is to parse strings into other numbers and strings so that things like atoi() are not required. Also in C++ it is considered a better practice to declare your variables closer to first use instead of in one large lump at the beginning of the program.

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
#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;

int main() {
    ifstream input("input.txt");
    if(!input)
    {
        std::cerr << "Error opening input file.\n";
        return(1);
    }

    ofstream output("output.txt");
    if(!output)
    {
        std::cerr << "Error opening output file.\n";
        return(2);
    }

    string line;

    // Read the entire line into a string.
    while (getline(input, line)) {
        istringstream is(line);
        int numbers[3];
        char delimiter;
        // Parse the string with a stringstream.
        is >> numbers[0];
        for(int i = 1; i < 3; ++i){
            is >> delimiter >> numbers[i];
        }

        string text;
        // Get the text line from the file.
        getline(input, text);

        int sum = 0;

        for (int i = 0; i < 3; i++) {
            sum += numbers[i];
        }

        // Create a stringstream to hold the repeated text.
        ostringstream os;
        os << text;
        for (int i = 1; i < sum; i++) {
            os  << ", " << text;
        }
        // Output the stringstream to the file and the console.
        cout << os.str() << endl;
        output << os.str() << endl;
    }

    return 0;
}


Last edited on
Topic archived. No new replies allowed.