-2

我希望能够得到一条线并将其拆分为不同类型的变量(使用标准 c++ 库)。所以这个输入行:

C 56 99.7 86.7 9000

将按空格字符“爆炸”到这些变量:

Char
std:string
double
double
double

这就是我目前处理给定输入的方式:

#define MAX_LINE 200

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

是否有像getline()我这样的特殊功能可以用来分离给定的输入并将这些输入分配给变量(使用强制转换或类似方法)?

4

2 回答 2

2

使用>>运算符得到你想要的

#include <iostream>

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

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

你可以在这里阅读更多关于它的信息

于 2013-01-01T14:54:10.973 回答
0

不要使用 getline(),而是使用 istream 运算符 >>。

这些是此运算符的重载:

// 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;
于 2013-01-01T15:01:10.340 回答