2016-05-08 4 views
-1

catchクラスから例外クラスのwhat()関数を呼び出していますが、what()関数がガベージ値を出力していますそれはcheckusername()関数からスローされた値を出力する必要があるのではなく、値が割り当てられていないので、私には助けてください。ここreturn声明を持っていないコード例外クラスの関数をcatchブロックから呼び出すと、tryブロックから渡された値が出力されない

#include <iostream> 
#include <string> 
#include <sstream> 
#include <exception> 
using namespace std; 
class BadLengthException 
{ 
public: 
int n1; 
BadLengthException(int n) 
{ 
    n1=n; 
    } 
int what() 
    { 
    cout << n1; 
    } 
}; 
bool checkUsername(string username) { 
bool isValid = true; 
int n = username.length(); 
if(n < 5) { 
    throw BadLengthException(n); 
} 
for(int i = 0; i < n-1; i++) { 
    if(username[i] == 'w' && username[i+1] == 'w') { 
     isValid = false; 
    } 
} 
return isValid; 
} 

int main() { 
int T; cin >> T; 
while(T--) { 
    string username; 
    cin >> username; 
    try { 
     bool isValid = checkUsername(username); 
     if(isValid) { 
      cout << "Valid" << '\n'; 
     } else { 
      cout << "Invalid" << '\n'; 
     } 
    } catch (BadLengthException e) { 
     cout << "Too short: " << e.what() << '\n'; 
    } 
} 
return 0; 
} 

答えて

0

whatであるため、未定義の動作を引き起こしています。 cout << n1の代わりにreturn n1があると思われます。

関連する問題