-1

I'm reading in a line of input from a file such as "5 8 12 45 8 13 7".

Could I put these integers directly into an array, or must I put them into a string first?

If it's mandatory to initially use a string, how would I convert this string of integers into an array?

input: "5 8 12 45 8 13 7" => into an array as such: {5,8,12,45,8,13,7}

Aaron Porter
  • 325
  • 1
  • 4
  • 7
  • How are you reading the line? Please post that code: it is relevant. – Waleed Khan Feb 06 '13 at 22:03
  • 2
    I believe this question to be a duplicate of the following: http://stackoverflow.com/questions/1321137/convert-string-containing-several-numbers-into-integers http://stackoverflow.com/questions/1894886/parsing-a-comma-delimited-stdstring http://stackoverflow.com/questions/4170440/regex-how-to-find-the-maximum-integer-value-of-a-pattern http://stackoverflow.com/questions/2619227/best-way-to-get-ints-from-a-string-with-whitespace http://stackoverflow.com/questions/1141741/int-tokenizer – Sami Kenjat Feb 07 '13 at 02:28

1 Answers1

7

No, you don't need to convert them into a string. With the containers and algorithms of the C++ Standard Library it is actually pretty easy (this works as long as the separator is a white space or a sequence of white spaces):

#include <iterator>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v;

    // An easy way to read a vector of integers from the standard input
    std::copy(
        std::istream_iterator<int>(std::cin), 
        std::istream_iterator<int>(), 
        std::back_inserter(v)
        );

    // An easy wait to print the vector to the standard output
    std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
}
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • How would I print this array? Sorry, I'm struggling hard with this language. – Aaron Porter Feb 06 '13 at 23:12
  • @AaronPorter: I added a simple way to print the vector to the standard output. Please consider accepting this answer if it helped you. – Andy Prowl Feb 06 '13 at 23:53
  • 3
    @AndyProwl He could also consider reviewing the list of duplicate questions that cover this particular problem to death. – Sami Kenjat Feb 07 '13 at 03:32
  • @SamiKenjat: Oh sure that's another good thing he could have done in the first place, but since he did not do it and rather he's asking me further questions I'd appreciate him to accept this answer at least. Just so I don't feel completely like a help desk. – Andy Prowl Feb 07 '13 at 06:22