Bryan
Bryan

Reputation: 117

Extracting individual value from string using stringstream

So I have the txt file, input.txt that I am reading into my program. I was able to get the first line of numbers using the getline function and now I am trying to get each number. I will be putting these numbers into a BST, but I am not concerned with this part, just how to get each number. From what I can gather I need to use stringstream but I am stuck on how to extract each number and be able to add them individually.

BST.cpp

#include "stdafx.h"
#include "BST.h"
#include <iostream>
#include <cstddef>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;


int main()
{
    BST<int> B;
    fstream input;
    input.open("input.txt", ios::in);
    string number;
    stringstream ss;

    if(input.fail())
        cout << "File was not opened successfully" << endl;
    else
        cout<< "File was opened succesffuly" << endl;

    getline(input,number,'\n');
    cout << number << endl;
    ss << number;

    return 0;
}

input.txt

12 6 9 45 3 7 10 2 4 13
4
9
55 18 3 6 78 9
13
66
808 707 909 1001 505 1200 499 644 1190 1592
707
78

Upvotes: 1

Views: 918

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

Like this:

std::string line;
int line_number = 1;
while (std:getline(input, line))
{
    std::cout << "Line #" << line_number++ << ':';

    std::istringstream os(line);

    int number;
    while (os >> number)
        std::cout << ' ' << number;

    std::cout << '\n';
}

For the first three line of your input, it should print

Line #1: 12 6 9 45 3 7 10 2 4 13
Line #2: 4
Line #3: 9

Upvotes: 1

Related Questions