我想获取用户输入的ID的各个数字的总和。到目前为止,这是我拥有的代码,我的代码可以计算用户输入中的字符数,但我希望它也计算各个数字的总和。
// user prompt for student id
cout << "Type in your student login ID: ";
string studentId;
// user input of student ID
getline(cin, studentId);
// computer output of studentId
cout << "Student ID Sum: " << studentId.length() << endl;
只需使用基于范围的 for 循环。举例来说
unsigned int sum = 0;
for ( const auto &c : studentId )
{
if ( '0' <= c && c <= '9' ) sum += c - '0';
}
std::accumulate
中的 <numeric>
来实现此目的,迭代字符串 s
并将每个字符的数值添加到累加器(如果它是数字)。
#include <string>
#include <iostream>
#include <numeric>
#include <cctype>
int main() {
std::string s = "456";
std::cout << std::accumulate(
s.begin(), s.end(), 0,
[](unsigned int i, char &ch){
return std::isdigit(ch) ? i + (ch - '0') : i;
}
) << std::endl;
return 0;
}
打印:
15
在 for 循环中逐个字符读取字符串,并通过将其添加到总和中将字符隐藏为整数
int sum =0;
for (int i=0; i< studentId.length(); i++){
sum = sum + ((int)studentId[i] - 48);
}
cout<<sum;
您还可以借助输入和输出格式来完成。
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string s = "2342";
std::istringstream iss {s};
std::ostringstream oss;
// so that stream can look like : 2 3 4 2
// adding whitespace after every number
for (char ch; iss >> ch;) {
oss << ch << ' ';
}
std::string new_string = oss.str();
std::istringstream new_iss {new_string};
// read individual character of string as a integer using input
// formatting.
int sum = 0;
for (int n; new_iss >> n;) {
sum += n;
}
std::cout << "sum :" << sum << '\n';
}