2017-10-18 4 views
-1

私は2つの数字mとnを入力として受け取り、m番目の数字のn番目の桁を与えます。例M = 1358、N = 2出力:5エラー:変数がこのスコープで宣言されていませんでした。C++

#include <iostream> 
#include <string> 
using namespace std; 

int main(){ 
    while(true){ 
     int m = 0,n = 10; 
     char check; 
     while(true){ 
      cout << "Enter please number m and which digit you want to select"; 
      cin >> m >> n; 
      string m_new = to_string(m); 
      if(m_new.length() > n) 
       break; 
      else 
       cout << "n must be less than or equal to m";  
     } 
     cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1); 
     cout << "Do you want to try again?(y/n)\n"; 
     cin >> check; 
     while(check != 'y'&& check != 'n'){ 
      cout <<"Please enter y or n\n"; 
      cin >> check; 
     } 
     if(check == 'n'){ 
      break; 
     } 
    } 
    return 0; 
} 

しかし、私はエラーました: 'm_newは' このスコープで宣言されていませんでした。なぜこのエラーが発生し、それを修正するのですか?

答えて

3

m_newがwhileループ内で宣言されています。 {...}ブロック内に宣言されたものは、そのブロック内にのみ存在します。最終的に使用する:

cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1); 

はブロックの外にあり、変数はもはや存在しません。

+0

@DreamsOfElectricSheepありがとうございます(同時にスポーツを見ようと私に奉仕します...) – Steve

4

変数m_newは、ネストされたwhileループにローカルであり、その範囲外では使用できません。

int main(){ 
    char check = 'y'; 
    while (std::cin && choice == 'y') { 
     int m = 0, n = 10; 
     std::cout << "Enter please number m and which digit you want to select"; 
     std::cin >> m >> n; 
     string m_new = to_string(m); 
     // the rest of your code 
     std::cout << "Please enter y or n\n"; 
     std::cin >> check; 
    } 
} 

m_new変数はwhileループ内すべてに見える:

int main() { 
    // can't be used here 
    while (true) { 
     // can't be used here 
     while (true) { 
      string m_new = to_string(m); 
      // can only be used here 
     } 
     // can't be used here 
     while (check != 'y'&& check != 'n') { 
      // can't be used here 
     } 
     // can't be used here 
    } 
    // can't be used here 
} 

設計は一whileループを使用することを再考:ブレース{}で表される範囲が視認性を判断します。

+0

'to_string'は、ユーザーが入力した値 –

関連する問題