如何从输入字符串中分离整数并将其转换为int类型以允许对其进行计算
How to seperate integers from input string and convert them to type int to allow calculations on them
正如Mehdi Algholipour所写的
1。从输入
中获取字符串2。单独输入整数
3。保存到数组
cout << "Give me some integers separated with space";
cin >> string; // example input 10 210 300 510
//..some code that seperate input to integer numbers and save them to Array
//EXPECTED RESULT: Array[0]=10 Array[1]=210 etc...
我想你的意思是:
- 从输入 获取
- 单独输入
Integer
号 - 保存到
Array
string
如果这是你的平均值,试试下面的代码:
string str;
int arr[1000]; // I supposed 1000 is your Int Array size.
int number = 0, index = 0;
getline(cin, str); // Get a line of string
for (int i = 0 ; i < str.length() ; i++){ // Processing your str Array
if (isdigit(str[i])){
number *= 10;
number += ((int)str[i] - '0');
}
else {
arr[index++] = number;
number = 0;
}
}
arr[index] = number; // for last element of your input
// Do something you want
尝试:
#include <iostream>
#include <string>
#include <vector>
#include <regex>
int main()
{
std::regex rgx("\b\d+\b");
std::string line;
std::cout << "Please enter numbers separated by spaces and press enter:" << std::endl;
std::getline(std::cin, line);
std::sregex_iterator it(line.begin(), line.end(), rgx);
std::sregex_iterator end;
std::vector<int> values;
std::transform(it, end, std::back_inserter(values), [](std::smatch s){ return std::stoi(s.str()); });
for (int v : values)
std::cout << v << std::endl;
}
使用stringstream
:
string str;
getline(cin, str);
stringstream ss(str);
vector<int> vec;
int Integer;
while(true)
{
ss >> Integer;
if(!ss)
break;
vec.push_back(Integer);
}
现场演示
注意:您需要包括以下标题:<string>
, <sstream>
, <vector>
相关文章:
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 指针问题:从不兼容的类型"int"分配给"int *"
- 数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值
- 错误:数组下标的类型"int[int]"无效
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 类型为 "int*" 的参数与 C++ 中错误类型"int**"参数不兼容
- 类型"int"和"const char [15]"到二进制"运算符<<"的无效操作数^
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- for 循环说 - 错误 成员引用基类型"int [13]"不是结构或联合
- 运行时错误:有符号整数溢出:964632435 * 10 无法在类型 'int' 中表示
- 如何增加模板类型 int 参数?
- 尝试使用 Array 类的模板构造整数数组时,错误:为什么数组类型"int [5]"不可分配,
- 如何为底层类型 int 的枚举专门化类
- 数组下标编译的无效类型'int[int]'由于 -Wfatal 错误而终止
- 不能将 "const char*" 类型的值分配给类型 "int" 的实体
- 数组下标的无效类型INT [INT]
- 请求在"伺服控制器"中请求成员"附加",该成员属于非类类型"int"
- 数组类型 'int [8]'不可分配
- 未声明的标识符和类型"int"从 main 调用类时出现意外错误