2012-10-18 29 views
7

我发现这个代码在网上为做一个字符串漂浮/ INT /双转换的模板。这是只有在这里,所以我有东西要给问题引用....字符串浮动使用字符串流

我想有一个用户输入一个数字作为一个字符串,将其转换为float,测试它的成功和辍学,如果进入了“ Q'或打印“无效输入”(如果它不是'Q'uit'字符并返回更多输入。

什么是一个转换的语法测试失败?会不会是ss.fail()?

// using stringstream constructors. 
#include <iostream> 
#include <sstream> 
using namespace std; 

int main() { 

    int val; 
    stringstream ss (stringstream::in | stringstream::out); 

    ss << "120 42 377 6 5 2000"; 

    /* Would I insert an 

    if(ss.fail()) 
     { 
     // Deal with conversion error } 
     } 

    in here?! */ 


    for (int n=0; n<6; n++) 
    { 
    ss >> val; 
    cout << val*2 << endl; 
    } 

    return 0; 
} 
+0

你做了什么语法错误? –

回答

9

您的代码不是很有帮助。但是,如果我理解你的权利做这样的

string str; 
if (!getline(cin, str)) 
{ 
    // error: didn't get any input 
} 
istringstream ss(str); 
float f; 
if (!(ss >> f)) 
{ 
    // error: didn't convert to a float 
} 

有没有必要使用失败。

2

其实,做串浮充转换最简单的方法可能是boost::lexical_cast

#include <string> 
#include <boost/lexical_cast.hpp> 

int main() { 
    std::string const s = "120.34"; 

    try { 
     float f = boost::lexical_cast<float>(s); 
    } catch(boost::bad_lexical_cast const&) { 
     // deal with error 
    } 
} 

显然,在大多数情况下,你只是不捕获异常,马上让它泡了调用链,所以成本大大降低。

0

一些通过原题要求的特点是:

  1. 输出两次输入的值浮动
  2. 报告无效输入
  3. 继续在遇到无效输入
  4. 后找花车看到“Q”字

我认为下面的代码符合ABO后停止五个要求:

// g++ -Wall -Wextra -Werror -static -std=c++11 -o foo foo.cc 

#include <iostream> 
#include <sstream> 

void run_some_input(void) 
{ 
    std::string  tmp_s; 

    int not_done = 1; 

    while(not_done && getline(std::cin, tmp_s)) 
    { 
     std::stringstream ss; 

     ss << tmp_s; 

     while(! ss.eof()) 
     { 
      float tmp_f; 
      if (ss >> tmp_f) 
      { 
       std::cout << "Twice the number you entered: " 
          << 2.0f * tmp_f << "\n"; 
      } 
      else 
      { 
       ss.clear(); 
       std::string tmp_s; 
       if(ss >> tmp_s) 
       { 
        if(! tmp_s.compare("Q")) 
        { 
         not_done = 0; 
         break; 
        } 
        std::cout << "Invalid input (" << tmp_s << ")\n"; 
       } 
      } 
     } 
    } 
} 

int main(int argc __attribute__ ((__unused__)), char **argv __attribute__ ((__unused__))) 
{ 
    run_some_input(); 
} 

这里有一个样本会话:

$ ./foo 
1 
Twice the number you entered: 2 
3 4 
Twice the number you entered: 6 
Twice the number you entered: 8 
5 bad dog Quit 6 8 Q mad dog 
Twice the number you entered: 10 
Invalid input (bad) 
Invalid input (dog) 
Invalid input (Quit) 
Twice the number you entered: 12 
Twice the number you entered: 16