Linell
Linell

Reputation: 749

Reading Strings and Ints from the Same File

Given input in the form of

fifteen,7,fourth-four,2,1,six
66,eight-six,99,eighteen
6,5,4,3,2,1

What can I use to read this into a format that I can then parse? The goal is to be able to sort the numbers and then print them back out, in order, in the same format that they were given to me. For example, the following should be printed as

    1,2,six,7,fifteen,forty-four
    eighteen,66,eighty-six,99
    1,2,3,4,5,6

I have an idea of how the sorting should be done, I'm just having trouble figuring out the best way to read in the input. Currently, I'm using just doing this:

#include <iostream>
#include <string>
using namespace std;

int main() {
    char word;
    char arr[20];

    int count = 0;

    while (cin >> word) {
        if (word == '\n') {
            cout << "Newline detected.";
        }
        cout << "Character at: " << count << " is " << word << endl;
        count++;
    }
}

This does not work, because there is never a \n read in.

Upvotes: 0

Views: 76

Answers (1)

john.pavan
john.pavan

Reputation: 950

IMO the easiest way to do it would be to use std::istream's getline function with the ',' as the delimiter.

E.g. Something like.

char dummystr[256];
int count = 0;
while (cin.getline(dummystr, 256, ',')) {
    cout << "Character at: " << count << " is " << dummystr << endl;
    ++count;
}

For newline delimiters with comma delimiters on each line (you really should just pick one):

char dummystr[256]; // not max size for the string
int count = 0;
while (cin.getline(dummystr, 256, '\n')) {
    std::stringstream nested(dummystr);
    char dummystr2[256];
    while (nexted.getline(dummystr2, 256, ',')) {
        cout << "Character at: " << count << " is " << dummystr << endl;
        ++count;
    }
}

Upvotes: 2

Related Questions