2013-08-31 74 views
-4

我知道这个问题在stackoverflow之前已经被问过很多次,但是这里没有类似于我的问题。C++错误:从'int'到'const char *'的无效转换

所以我有上面提到的错误:从“诠释”到“为const char *”

我不认为“is_distinct(字符串年)”功能有什么用这一点,但无效的转换为了以防万一,我粘贴了它。

这里是我的代码:

#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; 
} 
+1

while循环'1 == 1'可以写为TRUE;或只是'1'这可能是更容易阅读。 – Celeritas

+0

您不能有多个相同名称的变量。 int年,然后在下一行中输入年份。 – dcaswell

+0

您提到的错误消息在哪里? – Potatoswatter

回答

3

int year = to_int(year);

year要传递到to_int是你刚刚宣布同int year,在main顶部string year声明。

0

while循环也许应该是这样的:

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

    else { 
     year = to_str(int_year+1); 
    } 
} 
相关问题