如何从输入字符串中分离整数并将其转换为int类型以允许对其进行计算

How to seperate integers from input string and convert them to type int to allow calculations on them

本文关键字:类型 int 计算 转换 字符串 输入 分离 整数      更新时间:2023-10-16

正如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...
我想你的意思是:
  1. 从输入
  2. 获取string
  3. 单独输入Integer
  4. 保存到Array

如果这是你的平均值,试试下面的代码:

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>