Take the 2-minute tour ×

I want to be able to get a line and split it to different types of variables (using standard c++ libraries). So this input line:

C 56 99.7 86.7 9000

Will "explode" by a space char to these variables in order:


This is how I currently handle the given input:

#define MAX_LINE 200

char line[MAX_LINE];
cout << "Enter the line: ";
cin.getline (line,MAX_LINE);

Is there some special function like getline() i can use to separate the given input and assign these input to variables (with casting or similar)?

share|improve this question
Read further on in your C++ book. It teaches you about formatted extraction from streams. –  Lightness Races in Orbit Jan 1 '13 at 14:51
Tokenize you string and after, using some try/catch blocks convert into desired data tyoes. –  user1929959 Jan 1 '13 at 14:53

2 Answers 2

up vote 2 down vote accepted

Use the >> operator to get what you want

#include <iostream>

int main()
    char c;
    double d;
    std::cin >> c >> d;

    std::cout << "The char was: " << c << ", the double was:" << d;    

You can read more about it here

share|improve this answer

Instead of using getline(), use istream operator >>.

These are the overloads for this operator:

// Member functions  :

istream& operator>> (bool& val );
istream& operator>> (short& val );
istream& operator>> (unsigned short& val );
istream& operator>> (int& val );
istream& operator>> (unsigned int& val );
istream& operator>> (long& val );
istream& operator>> (unsigned long& val );
istream& operator>> (float& val );
istream& operator>> (double& val );
istream& operator>> (long double& val );
istream& operator>> (void*& val );
istream& operator>> (streambuf* sb );
istream& operator>> (istream& ( *pf )(istream&));
istream& operator>> (ios& ( *pf )(ios&));
istream& operator>> (ios_base& ( *pf )(ios_base&));

// Global functions :
istream& operator>> (istream& is, char& ch );
istream& operator>> (istream& is, signed char& ch );
istream& operator>> (istream& is, unsigned char& ch );
istream& operator>> (istream& is, char* str );
istream& operator>> (istream& is, signed char* str );
istream& operator>> (istream& is, unsigned char* str );

char ch;
std:string str;
double d;

cin >> ch >> str >> d;
share|improve this answer
You could have just given the link instead of writing them all over. –  Coding Mash Jan 1 '13 at 15:05

Your Answer


