我想从字符串中的值执行数学运算

I want to perform a mathematical operation from values in a string

本文关键字:执行数 运算 字符串      更新时间:2023-10-16
string resistance;
ifstream in;
in.open(filename);
while (!in.eof())
{
    getline(in, resistance);
    cout << resistance <<endl;
}
in.close();

这是我用来从文件中读取的代码。该文件的输出为:例如:

10

25 10 60 45 35

10 45 23 45 65 88

我想取每行,并通过行的每个值对变量执行数学运算

首先,拆分字符串,然后使用 atoi 将它们转换为数字,然后遍历那些正在执行操作的值。

在 C++11 中,您可以使用 std::stoi 函数:

istringstream iss( resistance);
istream_iterator<string> it = iss.begin();
while( it != iss.end()) {
    int value = stoi( *it++);
    //... do something
}