如何将给定字符串从输入分割为不同类型的变量
How to split a given string from input to different types of variables?
我希望能够获得一行并将其拆分为不同类型的变量(使用标准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;
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- CRTP 模式 但是在数据结构中存储非同构类型
- 私有结构(在类中定义)不能用作属于同一类的函数的返回类型吗
- C++ 管理多个同质数据类型
- 在同一行读取具有多个类型的文件
- C++对同一类类型的引用公开私有成员
- 在同一类中向前声明类型
- 用于逻辑分割的非类型模板
- 如何将给定字符串从输入分割为不同类型的变量