Convert String containing several numbers into integers


I realize that this question may have been asked several times in the past, but I am going to continue regardless.

I have a program that is going to get a string of numbers from keyboard input. The numbers will always be in the form "66 33 9" Essentially, every number is separated with a space, and the user input will always contain a different amount of numbers.

I'm aware that using 'sscanf' would work if the amount of numbers in every user-entered string was constant, but this is not the case for me. Also, because I'm new to C++, I'd prefer dealing with 'string' variables rather than arrays of chars.

8/24/2009 8:32:38 AM

Accepted Answer

I assume you want to read an entire line, and parse that as input. So, first grab the line:

std::string input;
std::getline(std::cin, input);

Now put that in a stringstream:

std::stringstream stream(input);

and parse

while(1) {
   int n;
   stream >> n;
   std::cout << "Found integer: " << n << "\n";

Remember to include

#include <string>
#include <sstream>
8/24/2009 8:38:19 AM

The C++ String Toolkit Library (Strtk) has the following solution to your problem:

#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
#include <iterator>

#include "strtk.hpp"

int main()
   std::string s = "1 23 456 7890";

   std::deque<int> int_list;
   strtk::parse(s," ",int_list);


   return 0;

More examples can be found Here

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow