开发者

C++: how do I convert a string into a float where the starting char can change?

开发者 https://www.devze.com 2023-01-13 04:50 出处:网络
I have this kinda 开发者_StackOverflow社区of input: x4.9 x.25 C400 What is the best way to drop the first char and convert to float?You can use sscanf(), eg:

I have this kinda 开发者_StackOverflow社区of input:

x4.9
x.25
C400

What is the best way to drop the first char and convert to float?


You can use sscanf(), eg:

#include <stdio.h>

float f; 
char *str = "x4.9"; 

if( sscanf(str, "%*c%f", &f) == 1 )
{
    // use f as needed ...
}


#include <iostream>

...
char c;
float f; 
std::cin >> c >> f;

std::cin >> c reads one character from standard input and stores the character in c, and std::cin >> f reads and stores one float from standard input. std::cin >> c >> f is equivalent to std::cin >> c; std::cin >> f;

You can loop something like the above to read a series of inputs. cin skips over whitespace by default, so the newlines won't be an issue.


Your input is line-oriented, so you might want to read lines first, and then process these:

// Beware, brain-compiled code ahead!
void process_line(std::istream& is);

void read_input(std::istream& is)
{
  while(is.good()) {
    std::string line;
    //is >> std::ws;            // might want to allow leading whitespace
    std::getline(is,line);
    if(is && !line.empty()) {
      std::istringstream iss(line); 
      process_line(iss);
      if(!iss.eof())            // reading number failed
        break;
    }
  }
  if(!is.eof()) // reading failed before eof
    throw("input error, read_input() blew it!");
}

void process_line(std::istream& is)
{
  char ch;
  double d;
  is >> ch >> d/* >> std::ws*/; // trailing whitespace usually often is acceptable
  if(!is.eof())                 // should be at the end of line
    return;
  process_number(ch,d);         // I don't know whether ch is important
}

Error handling could be improved, but this should give you a start.

0

精彩评论

暂无评论...
验证码 换一张
取 消