0

If I prompt the user to enter 6 numbers in one line, for example:

3 4 5 6 7 8

How can I store the first number in the string into variable Num1, 2nd number into variable Num2, 3rd number into variable Num3, etc.? I.e., I need to prompt the user to input a single line containing 6 different numbers, and then split those 6 numbers into 6 different variables.

This is my code:

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

int main()
{
    string num;
    cout << "Enter one line containing 6 integers" << endl; 
    getline(cin, num)

    return 0;
}

Not sure if string is the right type to use.

And this method causes all 6 numbers to be stored into num instead of splitting the 6 numbers up into separate variables.

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
user3281580
  • 53
  • 1
  • 2
  • 5

3 Answers3

0

You can do like:

cin>>num1>>num2>>num3>>num4>>num5>>num6;

c++ breaks string on space characters.

Use 'cin' in place of 'getline'.

Swapnil R Mehta
  • 117
  • 1
  • 12
0

In C you can use split strings with strtok.

See this tutorial: http://www.c-howto.de/tutorial-strings-zeichenketten-stringfunktionen-zerteilen-strtok.html

For C++ we have already a question that might answer your needs: Split a string in C++?

Hope this helps you.

Community
  • 1
  • 1
GreatSUN
  • 50
  • 3
0

You can do what you are asking like this

std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
iss >> num1 >> num2 >> num3 >> num4 >> num5 >> num6;

However, I would highly encourage you to look into a container (e.g. std::array, std::vector, std::list);

Zac Howland
  • 15,777
  • 1
  • 26
  • 42