【发布时间】:2014-12-11 09:50:40
【问题描述】:
我目前正在尝试获取用户输入的数字字符串,将它们单独转换为 int,然后合计它们的总和。
EX:如果用户输入“1234”,程序应该执行 1 + 2 + 3 + 4 并显示“10”。我尝试了很多实验,但似乎停滞不前。
我希望使用 C-string/String 对象创建此代码,并尽可能使用“istringstream()”(虽然没有必要...[特别是如果有更简单的方法...])
这是我目前所拥有的:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string digits;
int total = 0, num;
cout << "Enter a string of digits, and something magical will happen to them..." << endl;
cin >> digits;
for (int i = 0; i < digits.length(); i++)
{
cout << digits.at(i) << endl;
istringstream(digits.at(i)) >> num;
cout << num << endl; // Displays what came out of function
total += num;
}
cout << "Total: " << total << endl;
// Digitize me cap'm
// Add string of digits together
// Display Sum
// Display high/low int in string
}
我做错了什么?为什么我在 for 循环中不断获得超高数字?我应该使用更有效的功能吗?谢谢你的帮助:)
【问题讨论】:
-
istringstream(digits.at(i))甚至不应该编译,您使用的是什么编译器/标准库?
标签: c++ string object sum c-strings