2012-03-22 87 views
11

我想了解stringstream作品爲了如何能夠識別並轉換是被輸入的字符串作爲可能的數字...由於某種原因,這一小段代碼,我寫了嘗試和了解stringstream是被惱人的幾個錯誤...stringstream的錯誤C++

#include <iostream> 
#include <string> 

using namespace std; 

int str2int (const string &str) { 
    std::stringstream ss(str); 
    int num; 
    if((ss >> num).fail()) 
    { 
     num = 0; 
     return num; 
    } 
    return num; 
} 

int main(){ 
    int test; 
    int t = 0; 
    std::string input; 
    while (t !=1){ 
     std::cout << "input: "; 
     std::cin >> input; 
     test = str2int(input); 
     if(test == 0){ 
      std::cout << "Not a number..."; 
     }else 
      std::cout << test << "\n"; 
     std::cin >> t; 
    } 
    return 0; 
} 

錯誤:

Error C2079:'ss' uses undefined class std::basic_stringstream<_elem,_traits,_alloc>' 
Error C2228: left of '.fail' must have class/struct/union 
Error C2440: 'initializing': cannot convert 'const std::string' into 'int' 

我究竟做錯了什麼?

+1

不是錯誤消息背後的原因,但有一件事你錯誤的是使用'stringstream',當你應該使用'istringstream'。 (使用'fail'也不是很習慣。) – 2012-03-22 09:33:13

回答

22

您需要包括下面的頭文件 -

#include <sstream> 

每當你看到這樣undefined class錯誤,你應該總是尋找第一個丟失的頭文件。

Herestringstream類的文檔。

1

包含此:

#include <sstream> 

而且,這樣寫:

if(ss >> num) //no .fail() 
{ 
    return num; //read succeeded 
} 
return 0; //read failed 

順便說一句,你可以在main()使用std::cin >> test本身:

int main(){ 
    int test; 
    int t = 0; 
    while (t !=1){ 
     std::cout << "input: "; 
     if (std::cin >> test) 
      std::cout << test << "\n"; //read succeeded 
     else 
      std::cout << "Not a number..."; //read failed 
     std::cin >> t; 
    } 
    return 0; 
} 

不需要str2int功能!

+1

或者簡單的'return ss >> num? num:0;'? (儘管我可能會將'>>'分隔成單獨的語句。'ss >> num; return ss?num:0;'。) – 2012-03-22 09:35:02

+0

@JamesKanze:很好。 :-) – Nawaz 2012-03-22 09:42:11

3

要使用stringstream,您需要做;

#include <sstream> 

之後,似乎一切工作,因爲它應該。

+0

smdh ...我應該去睡覺哈哈。那種缺乏關注是不可接受的......謝謝。 – 2012-03-22 05:44:52

3

你需要包括sstream。

#include <sstream>

2

我需要添加 - 如果您的項目使用預編譯頭(例如,"stdafx.h"適用於Windows商店應用的Win32控制檯應用程序或"pch.h") - 請檢查它們包括提前<sstream>