• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 496
  • Last Modified:

How do I split a cin << string into integers?

Hey All,

I'm looking for a way to input 10 ints from a string.

I've tried the code below it doesn't work, since it is expecting th NULL. And other examples on here use char with built in text so that you can use NULL in the while loop. I then tried with the EOL but I run into char to int comparisons.

Ideally, I'd liek something simple like Java

 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        for (String s_in: args){
            System.out.println(s_in);
           
        }
       


Thank you

{
	char inputString[200];
	const char EOL = '\n';
	char delims[] = " ";
	char *result = NULL;
	result = strtok(inputString, delims);
	while (result != EOL)
	{
		// conver to int and add to Q here
	}
 
 
	/*
	fillQ[x].enqueue(768);
	fillQ[1].enqueue(685);
	fillQ[2].enqueue(767);
	fillQ[3].enqueue(663);
	fillQ[4].enqueue(250);
	fillQ[5].enqueue(755);
	fillQ[6].enqueue(386);
	fillQ[7].enqueue(893);
	fillQ[8].enqueue(544);
	fillQ[9].enqueue(740);
*/
}

Open in new window

0
cflores89
Asked:
cflores89
2 Solutions
 
evilrixSenior Software Engineer (Avast)Commented:
See if the example below helps. It assumes input is your string that you've already obtained from some other source. We put it into a stringstream and use this to pull out the int types. The example doesn't contain error handling, I leave that up to you.
#include <iostream>
#include <sstream>
#include <deque>
 
int main()
{
	char const input[] = "0 1 2 3 4 5 6 7 8 9\n";
 
	std::stringstream ss;
	ss << input;
 
	std::deque<int> myQueue;
	for(;;)
	{
		int i;
		ss >> i;
 
		if(ss.eof()) { break; }
		if(ss.bad()) { /* handle error */ break; }
 
		myQueue.push_back(i);
	}
 
	for(std::deque<int>::const_iterator itr = myQueue.begin() ; itr != myQueue.end() ; ++itr)
	{
		std::cout << *itr << std::endl;
	}
}

Open in new window

0
 
itsmeandnobodyelseCommented:
You can do

   string input;
   getline(cin, input);  // reads until the user types <enter>
   istringstream iss(input);
   int arr[100] = { 0 };
   int n = 0;
   while (n < (int)sizeof(arr)/sizeof(arr[0]) && iss>>arr[n])
          n++;

Then n is the number of integers entered.

>>>> Ideally, I'd liek something simple like Java
The Java code takes strings from an array and not integers from a string.
0
 
cflores89Author Commented:
Thank you very much! :)

stringstream was what i was looking for
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now