C ++当你不知道迭代何时结束时使用for循环

时间:2017-07-05 07:12:30

标签: c++ c++11

所以我有这个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中完成它

2 个答案:

答案 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()

获取字符串变量的长度。