0

我正在尝试从字符串中提取整数,例如用户输入可能是5ft12in或 5'12"`。

但是,当我的输入为 时,代码有效5ft1in,但在输入时无效5ft12in

我想遍历整个字符串并提取 3 个数字,如下所示:

feet = 5 
inches 1 =1 
inches 2 = 2   

但我似乎无法找到问题所在。

我认为有一种方法可以将输入转换为stringstream然后peek使用整个字符串char,但我不太确定如何。

string feet = "";
string inches = "";
string inches2 = "";

for (int i = 0; i < height.size(); ++i) {
    if (isdigit(height[i]) && (feet.empty())) {
        feet = height[i];
    } // end if

    else if ((isdigit(height[i]) && (!feet.empty()))) {
        inches = height[i];
    }

    else if ((isdigit(height[i]) && (!feet.empty() && (!inches.empty())))) {
        inches2 = height[i];
    } // end else if

}//end for

cout << "String of feet : " << feet << endl;
cout << "String of inches 1 : " << inches << endl;
cout << "String of inches 2 : " << inches2 << endl;
4

2 回答 2

0

在您的第二个if条件中,您没有检查inches的值,它是否为空。因此,当您的字符串“5ft12in”中的“2”在第二个if条件中被检查时,它非常满足它。因此,导致再次以英寸为单位存储值“2” ,而您实际上希望将其存储在英寸2中。

解决方案

string feet = "";

string inches = "";

string inches2 = "";

for(int i = 0; i < height.size(); ++i)
{

    if (isdigit(height[i]) && (feet.empty())) {         
        feet = height[i];
    } // end if 

    else if ((isdigit(height[i]) && (!feet.empty()) && (inches.empty())) {
            inches = height[i];
        }
    else if ((isdigit(height[i]) && (!feet.empty() && 
    (!inches.empty())))) {
            inches2 = height[i];
        } // end else if 

}//end for


    cout << "String of feet : " << feet << endl;
    cout << "String of inches 1 : " << inches << endl;
    cout << "String of inches 2 : " << inches2 << endl;
于 2017-05-18T20:08:55.100 回答
0

你根本不需要循环。

查看 的find_first_of()find_first_not_of()方法std::string,例如:

std::string feet;
std::string inches;

std::string::size_type i = height.find_first_not_of("0123456789");
feet = height.substr(0, i);

std::string::size_type j = find_first_of("0123456789", i);
i = height.find_first_not_of("0123456789", j);
if (i == std::string::npos) i = height.size();

inches = height.substr(j, i-j);

std::cout << "feet : " << feet << std::endl;
std::cout << "inches : " << inches << std::endl;

但是,这种模式搜索会更好地处理std::regex()(仅适用于 C++11 及更高版本):

#include <regex>

std::string feet;    
std::string inches;

std::smatch sm;
std::regex_match(height, sm, std::regex("(\\d+)\\D+(\\d+)\\D+"));
if (sm.size() == 3)
{
    feet = sm.str(1);
    inches = sm.str(2);
}

std::cout << "feet : " << feet << std::endl;
std::cout << "inches : " << inches << std::endl;

或者std::sscanf()

#include <cstdio>

int feet, inches;

std::sscanf(height.c_str(), "%d%*[^0-9]%d", &feet, &inches);

std::cout << "feet : " << feet << std::endl;
std::cout << "inches : " << inches << std::endl;
于 2017-05-18T22:38:20.257 回答