如何将给定字符串从输入分割为不同类型的变量

How to split a given string from input to different types of variables?

本文关键字:分割 同类型 变量 输入 字符串      更新时间:2023-10-16

我希望能够获得一行并将其拆分为不同类型的变量(使用标准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() i可以用来分离给定的输入,并将这些输入分配给变量(与铸造或类似)?

使用>>运算符来获得您想要的

#include <iostream>
int main()
{
    char c;
    double d;
    std::cin >> c >> d;
    std::cout << "The char was: " << c << ", the double was:" << d;    
}

你可以在这里阅读更多信息

不使用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;