C ++从字符串

时间:2017-05-18 19:35:26

标签: c++ sstream

我试图从字符串中提取整数,例如用户输入可能是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;

2 个答案:

答案 0 :(得分:0)

在第二个 if 条件下,如果它是空的,则不检查 inches 的值。因此,当&#34; 2&#34;从你的字符串&#34; 5ft12in&#34;在第二个 if 条件中检查,它非常满足它。因此,导致再次存储值&#34; 2&#34;在 inches 中,您实际上想要存储在 inches2 中。

<强>解决方案

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;

答案 1 :(得分:0)

根本不需要循环。

查看std::string的{​​{3}}和find_first_of()方法,例如:

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;

但是,使用find_first_not_of()代替(仅限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::regex()

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