我正在使用visual studio 2013社区来学习c ++入门.我遇到了这个问题.当我编写以下代码时,VS显示len未定义.
#include "stdafx.h"
#include<iostream>
#include<string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
string line;
while (getline(cin, line))
if (line.size() > 10)
auto len = line.size();
cout << line.size() <<" "<<len <<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我编写以下代码时,VS显示len已定义并且运行良好.
#include "stdafx.h"
#include<iostream>
#include<string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
string line("fewogwewjgeigeoewggwe");
auto len = line.size();
cout << line.size() <<" "<< len <<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我真的没有看到它的原因.希望得到一些好的解释.多谢!!!
您应该使用花括号编写正确的代码块.在您的第一个样本len超出范围
if (line.size() > 10)
auto len = line.size(); // <<< scope is local to this line
cout << line.size() <<" "<<len <<endl;
Run Code Online (Sandbox Code Playgroud)
你想要的是什么
if (line.size() > 10) { // <<<
auto len = line.size(); // <<< scope is local to the block
cout << line.size() <<" "<<len <<endl;
} // <<<
Run Code Online (Sandbox Code Playgroud)