繁体   English   中英

stringstream errors c ++

[英]stringstream errors c++

我试图理解stringstream如何工作,以便能够识别和转换作为字符串输入的可能数字...由于某种原因,我写的这小段代码试图理解stringstream正在讨厌一些错误。 ..

#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'

我究竟做错了什么?

您需要包含以下头文件 -

#include <sstream>

每当您看到undefined class等错误时,您应该始终首先查找缺少的头文件。

stringstream类的文档。

要使用stringstream,您需要这样做;

#include <sstream>

在那之后,一切似乎都应该工作。

你需要包括sstream。

#include <sstream>

我需要添加 - 如果您的项目使用预编译的头文件 (例如,对于Win32控制台应用程序为"stdafx.h"或对于Windows应用商店应用程序为"pch.h" ) - 请检查它们是否包含 <sstream>

包括这个:

#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功能!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM