输入字符串,其中Integer应为 - C ++

时间:2013-09-25 11:38:29

标签: c++ string integer sum

我是初学者,在完成Stroustrup的原则与实践时遇到了这么简单的问题。

仅使用基本元素

#include "std_lib_facilities.h"

int main()
{

double highest = 0;
double lowest = 100;
int i=0;
double sum = 0;
vector <double> inputlist;
double input;
string unit;

cout<<"Type in a number followed by it's unit \n";

while(cin>>input>>unit){

    inputlist.push_back(input);
    sum += inputlist[i];

    if (input >= lowest && input <= highest){
        cout<<input<<" \n";
        ++i;
    }

    else if (input < lowest){
        lowest = input;
        cout<<"\nLowest Number so far \n"<<lowest;
    ++i;
    }

    else if (input > highest){
        highest = input;
    cout<<"\nHighest number so far \n"<< highest;
    ++i;
    }

    else
        cout<<"Lowest is: \n"<<lowest<<"\n\n Highest is: \n"<<highest<<" \n\n and the total is: \n"<<sum;


    if (unit == "ft", "m", "in","cm")
        cout<<unit<<"\n";

    else
        cout<<"cannot recognize unit";
}

keep_window_open();
return 0;
}

我需要程序向用户显示字符“|”时的总和以及最高和最低值进入。问题是:我需要在输入Integer值的地方输入。

注意:我对转换知之甚少,但尝试了一些并且它们无效。

3 个答案:

答案 0 :(得分:3)

如果我理解正确,您想从int阅读std::cin,但是:

int i;
if (std::cin >> i) {
    ...

不符合您的需求,因为可能会有'|'个符号作为终止阅读的信号。

以下是您可以执行的操作:逐字逐句阅读输入(std::string)并使用临时std::istringstream分别解析这些单词:

std::string word;
if (std::cin >> word) {
    if (word == "|")
        ...
    // else:
    std::istringstream is(word);
    int i;
    if (is >> i) {
        // integer successfully retrieved from stream
    }
}

只是#include <sstream>

答案 1 :(得分:0)

用字符串读取值。如果它不匹配|使用以下函数将其转换为double:

double toDouble(string s)
{
   int sign = 1, i=0;
   if (s[0]=='-')
      sign = -1, i=1;

   double result = 0, result2 = 0;
   for (; i < s.size(); i++)
     if (s[i] == '.')
       break;
     else
       result = result * 10 + (s[i] - '0');

   for (i = s.size()-1 ; i>=0 ; i--)
     if (s[i] == '.')
        break;
     else
        result2 = result2 / 10 + (s[i] - '0');

   if (i>=0)
      result += result2/10;
   return result * sign;
}

答案 2 :(得分:0)

用英寸求和米没有多大意义。因此,您应该考虑将单位转换为比例因子。您可以使用地图来获取缩放因子。 即使这有点过冲,您也可以使用正则表达式来解析用户输入。如果正则表达式不匹配,您可以测试“|”之类的东西。 在新的c ++标准(http://en.wikipedia.org/wiki/C%2B%2B11)中,为此目的定义了一个正则表达式库。可惜的是,g ++正则表达式库是错误的。但是你可以使用boost(http://www.boost.org/doc/libs/1_54_0/libs/regex/doc/html/boost_regex/)。 这是一个例子:

#include <iostream>
#include <vector>
#include <map>
#include <boost/regex.hpp> //< Pittyingly std::regex is buggy.

using namespace std; ///< Avoid this in larger projects!
using namespace boost;

int main() {

const string strReFloat("([-+]?[[:digit:]]*\\.?[[:digit:]]+(?:[eE][-+]?[[:digit:]]+)?)");
const string strReUnit("([[:alpha:]]+)");
const string strReMaybeBlanks("[[:blank:]]*");
const string strReFloatWithUnit(strReMaybeBlanks+strReFloat+strReMaybeBlanks+strReUnit+strReMaybeBlanks);
const regex reFloatWithUnit(strReFloatWithUnit);

const map<const string,double> unitVal= {
    {"m", 1.0},
    {"in", 0.0254},
    {"ft", 0.3048},
    {"cm", 0.01}
};

double highest = 0;
double lowest = 100;
int i=0;
double sum = 0;
vector <double> inputlist;
double input;
double unitToMeter;
string unit;
string str;

while( (cout<<"\nType in a number followed by it's unit \n", getline(cin,str), str != "") ){

    smatch parts;

    if( regex_match(str,parts,reFloatWithUnit) ) {
        unit = parts[2].str();

        auto found = unitVal.find(unit);
        if( found != unitVal.end() ) {
            cout<<unit<<"\n";
            input = found->second * atof(parts[1].str().c_str());
        } else {
            cout << "Unit \"" << unit << "\" not recognized. Using meters.\n";
        }

        inputlist.push_back(input);
    sum += inputlist[i];

    if (input >= lowest && input <= highest){
        cout<<input<<" \n";
        ++i;
    }
    else if (input < lowest){
        lowest = input;
        cout<<"\nLowest Number so far \n"<<lowest;
    ++i;
    }

    else if (input > highest){
        highest = input;
                cout<<"\nHighest number so far \n"<< highest;
                ++i;
    }

    } else if( str == "|" ) {
        cout << "sum:" << sum << "\n";
    } else {
        cout << "Input not recognized.\n";
    }
}

return 0;
}