C ++错误:从'int'到'const char *'的转换无效

时间:2013-08-31 02:32:39

标签: c++

我知道在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;
}

2 个答案:

答案 0 :(得分:3)

  

int year = to_int(year);

您传递给year的{​​{1}}与您刚宣布的to_int相同, int year在顶部声明string year

答案 1 :(得分:0)

你的while循环应该是这样的:

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

    else {
        year = to_str(int_year+1);
    }
}