首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++:我在find()上遇到了麻烦

C++:我在find()上遇到了麻烦
EN

Stack Overflow用户
提问于 2021-04-16 08:35:18
回答 1查看 31关注 0票数 0

我对c++不是很有经验,而且我在编写一个学习字符串函数的程序时遇到了麻烦。我试过通过编写其他程序来单独测试这些功能来排除故障。

预期行为:它在“”之前确定一个名称,在后面确定一个整数。

演示行为:返回w/a空白名称和0。

我的平台是linux/x86。

代码语言:javascript
复制
//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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-16 08:44:16

尝试使用getline(cin,uni)。cin本身只读到第一个空格。此外,find()函数返回您搜索的字符串的位置。您可能也希望对gold使用substr()函数。

编辑:我相信您的意思是在find()函数括号外写'+1‘和'-1’,以获得空格前后的位置。这也可能导致错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67121824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档