2015-05-04 74 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