所以我有这个c ++代码(不是c ++ 11)
#include <iostream>
using namespace std;
int calcTrip (string s) {
int ans = 1;
for (int i = 0; i < sizeof(s); i++) {
char c = s[i];
ans = ((ans*(c - 'A' + 1)) );
}
return ans;
}
int main() {
string a1, a2;
cin >> a1 >> a2;
cout << calcTrip(a1) << endl;
if (calcTrip(a1) != calcTrip(a2)) {
cout << "STAY" << endl;
}
else {
cout << "GO" << endl;
}
}
对于i
中变量calctrip
中的for循环,如果我i<sizeof(s)
,我i
小于32,因为字符串的大小为32。由于字符串s
是用户输入,如何使i
小于用户输入中的字符数s。
P.S我知道如何在c ++ 11中这样做,但是对于课堂,我需要知道如何在c ++ 98中完成它
答案 0 :(得分:4)
要迭代C ++ 98中的std::string
(或任何Standard Containers),您也可以使用迭代器:
for(std::string::iterator it = s.begin(); it != s.end(); ++it) {
char c = *it;
ans = ((ans * (c - 'A' + 1)));
}
range-based for loop是C ++ 11的一个特性,但迭代器不是。另一种选择是使用简单的for
循环,如下所示:
for(int i = 0; i < s.size(); i++) {
char c = s[i];
ans = ((ans * (c - 'A' + 1)));
}
std::string::size
会返回std::string
中的字符数。
答案 1 :(得分:1)
sizeof运算符返回sizeof数据类型而不是变量。使用sizeof(s)将返回字符串的大小而不是a1的大小...所以可以使用,
a1.size() or a1.length()
获取字符串变量的长度。