C++ 错误:未在此范围c+;中声明变量+;
我想写一个程序,它以两个数字m和n作为输入,给出m的第n位数字。示例m=1358 n=2输出:5C++ 错误:未在此范围c+;中声明变量+;,c++,C++,我想写一个程序,它以两个数字m和n作为输入,给出m的第n位数字。示例m=1358 n=2输出:5 #include <iostream> #include <string> using namespace std; int main(){ while(true){ int m = 0,n = 10; char check; while(true){ cout << "Enter
#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;
}
#包括
#包括
使用名称空间std;
int main(){
while(true){
int m=0,n=10;
字符检查;
while(true){
cout>m>>n;
字符串m_new=到_字符串(m);
如果(m_new.length()>n)
打破
其他的
coutm_new
在while循环内声明。在{…}
块内声明的任何内容都将仅存在于该块内。它的最终用途:
cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1);
cout该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
}
重新考虑设计,仅使用一个,而循环:
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;
}
}
intmain(){
字符检查='y';
而(std::cin&&choice==“y”){
int m=0,n=10;
标准::cout>m>>n;
字符串m_new=到_字符串(m);
//代码的其余部分
标准::cout>检查;
}
}
现在,m_new
变量对while
循环中的所有内容都可见。@dreamsofectricsheep感谢(我在同一时间尝试观看体育比赛…)应该根据用户输入的值调用to_字符串