C++:我在使用 find() 时遇到了问题

C++: I'm having trouble with find()

我对 C++ 不是很有经验,而且我在编写 w/a 学习一些字符串函数的程序时遇到了问题。我尝试通过编写其他程序来单独测试功能来排除故障。

预期行为:它确定“”之前的名称和之后的整数。

已证明的行为:Returns w/a 空白名称和 0.

我的平台是linux/x86。

//I included my essential libraries and declared
//used functions.

#include <iostream>
using std::cout;
using std::cin;

#include <string>
using std::string;

int main()
{
    
    //Made the string and initialized it w/filler text.
    
    string uni="patchy 0000";
    cout << "Name the leprechaun and\ngive how much gold they have\n(seperate w/space please) \n";
    
    //I printed some text on the prompt
    //[addmitedly with bad formatting,]
    //and appended the input from the cin
    //function into "uni".

    cin >> uni;
    
    //Here I tried to find the name by
    //making a substring of everything
    //before the first " " in "uni", with
    //the numbers after being the value
    //of "gold".

    string nam=uni.substr(0,uni.find(" "-1));
    int gold=uni.find(" "+1);
 
    //Here's where the values are printed to
    //the console.

    cout << "Their name is " << nam << '!' << '\n';
    cout << "And, they have " << gold << " gold!" << '\n';
    return 0;
}

尝试使用 getline(cin, uni)。 cin 本身只读到第一个 space。 此外,find() 函数 returns 您搜索的字符串的位置。您可能也想对黄金使用 substr() 函数。

编辑:我相信您打算在 find() 函数括号外写上“+1”和“-1”以获得 space 前后的位置。这也可能导致错误。