-4

我知道这个问题之前在stackoverflow上已经被问过很多次了,但是没有一个和我类似的问题。

所以我遇到了上面提到的错误:从'int'到'const char *'的无效转换

我认为 'is_distinct(string year)' 函数与此无关,但我将其粘贴以防万一。

这是我的代码:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int to_int(string number);
string to_str(int number);
bool is_distinct(string year);

int main()
{
    string year = "";
    cout << "Enter a word: ";
    getline(cin, year);
    // given the year, 'year', we are to find the next year with distinct digits
    int int_year = to_int(year) + 1;
    while (1 == 1) {
        int year = to_int(year);
        string year = to_str(year);
        if (is_distinct(year)) {
            cout << year << endl;
            break;
        }

        else {
            year += 1;
        }
    }


    if (is_distinct(year)) {
        cout << year << " is a distinct year.";
    }

    else {
        cout << year << " is not a distinct year.";
    }
    return 0;
}

int to_int(string number) {
    int integer;
    istringstream(number) >> integer;
    return integer;
}

string to_str(int number) {
    stringstream ss;
    ss << number;
    string str = ss.str();
    return str;
}

bool is_distinct(string year) {
    bool distinct = true;
    for (unsigned int x = 0; x < year.length(); x++) {
        int counter = 0;
        for (unsigned int y = x+1; y < year.length(); y++) {
            if (year[x] == year[y]) {
                counter += 1;
            }
        }
        if (counter > 0) {
            distinct = false;
            break;
        }
    }
    return distinct;
}
4

2 回答 2

3

int year = to_int(year);

year你传递给的to_int就是int year你刚刚声明的,而不是 string yearmain.

于 2013-08-31T02:35:34.733 回答
0

您的 while 循环应该如下所示:

while (1){
    int_year = to_int(year);
    if (is_distinct(year)) {
        cout << year << endl;
        break;
    }

    else {
        year = to_str(int_year+1);
    }
}
于 2013-08-31T02:42:55.313 回答