String.at() 不与字符进行比较



我正在编写一个c++函数,该函数接受形式为"let_varname_=_20"的字符串,然后它将隔离"varname"以使用我的名称变量名称创建一个新字符串。我试图告诉。at()函数在遇到空格时停止迭代while循环(下划线是空格,我只是想让它非常清楚有一个空格)。然而,它没有正确地比较它们,因为它完全没有停止(传递2个空格)地走到字符串的末尾。

void store(std::string exp) {

int finalcount = 4;
char placeholder = ' ';
while (exp.at(finalcount)!=placeholder) {
    finalcount++;
}
for (int i = 0; i < exp.size(); i++) {
    std::cout << exp.at(i) << std::endl;
}

std::string varname = exp.substr(4, finalcount+1);
std::cout << finalcount + 1 << std::endl;
std::cout << varname << std::endl;

}

我从索引4开始,因为我知道索引0-3的字符串将是'l' 'e' 't'和' '。print语句只是我检查它读取的内容和我输入的内容(它读取的内容都很好,只是没有正确地进行比较)。我还试着让我的while循环条件说当char>65 &&<90来处理ASCII码,但这也不起作用。

提前感谢您的帮助。

您可以使用istringstream并将字符串视为流:

const std::string test_data = "let varname = 20";
std::istringstream test_stream(test_data);
std::string let_text;
std::string var_name;
char equals_sign;
unsigned int value;
test_stream >> let_text >> var_name >> equals_sign >> value;

这可能比你的代码容易得多。

编辑1:搜索字符串
您也可以使用std::string, find_first_offind_first_not_of方法。

std::string::size_type position = test_data.find_first_of(' ');
position = test_data.find_first_not_of(' ', position);
std::string::size_type end_position = test_data.find_first_of(' ');
let_text = test_data.substr(position, end_position - position);

问题是你没有正确使用substr(),正如我在评论中提到的。此外,正如Pete Becker在评论中提到的,您还应该检查=并在到达字符串末尾时停止,这样如果字符串中没有更多的空格,您就不会超出字符串。此外,在确定子字符串长度时,您不希望将1添加到finalcount,因为这样您的子字符串将包含使检查失败的空格或=

试试这个:

void store(std::string exp) {
    const int start = 4;          // <-- Enter starting position here.
    const char placeholder_space = ' '; // Check for space.
    const char placeholder_equal = '='; // Check for equals sign, as pointed out by Pete Becker.
    int finalcount = start;       // <-- Use starting position.
    bool found = false;
    while (finalcount < exp.size() && !found) {
        if (!((exp.at(finalcount) == placeholder_space) ||
              (exp.at(finalcount) == placeholder_equal))) {
            finalcount++;
        } else {
            found = true;
        }
    }
    if (!found) {
        std::cout << "Input is invalid.n"; // No ' ' or '=' found, put error message here.
        return;
    }
    for (int i = 0; i < exp.size(); i++) {
        std::cout << exp.at(i) << std::endl;
    }
    std::string varname = exp.substr(4, finalcount - start); // <-- Use starting position.
    std::cout << finalcount - start << std::endl; // Length of varname.
    std::cout << varname << std::endl;
}

最新更新