2015-05-04 67 views
0

我正在使用visual studio 2013社区来研究C++ primer。 而我遇到这个问题。 当我编写下面的代码时,VS显示len未定义。C++字符串:: size_type错误

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

当我编写下面的代码时,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; 
} 

我真的没有看到它的原因。希望得到一些很好的解释。多谢!!!

+3

C++是不是像Python的地方缩进是显著。输出不在'if' *或*循环中。 –

+1

在第一个代码块中,'cout'行不在'if'块中,因为没有大括号...因此'len'变量已经超出范围。加一些大括号。 – Buddy

+0

非常感谢大家。我的第一个问题。很高兴看到答案如此之快! – LiuHao

回答

6

你应该使用大括号写正确的代码块。在你的第一个样品len超出范围

if (line.size() > 10) 
     auto len = line.size(); // <<< scope is local to this line 
    cout << line.size() <<" "<<len <<endl; 

你想要的是

if (line.size() > 10) { // <<< 
     auto len = line.size(); // <<< scope is local to the block 
     cout << line.size() <<" "<<len <<endl; 
    } // <<< 
1

如果格式化你的代码,你会看到你的错误

while (getline(cin, line)) 
if (line.size() > 10) 
    auto len = line.size();   // variable len defined in this block .. 
cout << line.size() <<" "<<len <<endl; // .. and not defined here 
3

你缺少括号

if (line.size() > 10) 
{ 
    auto len = line.size(); 
    cout << line.size() <<" "<<len <<endl; 
} 

上面应该这样做。

更新:

学习新的编程语言后,我做的第一件事就是研究编码标准,并坚持下去。这将有助于很多方面,包括犯这样的错误。

有许多编码标准对于C++,所以你挑 http://en.wikipedia.org/wiki/Coding_conventions#Coding_conventions_for_languages

+0

Thx很多链接。 – LiuHao