我对c++不是很有经验,而且我在编写一个学习字符串函数的程序时遇到了麻烦。我试过通过编写其他程序来单独测试这些功能来排除故障。
预期行为:它在“”之前确定一个名称,在后面确定一个整数。
演示行为:返回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;
}发布于 2021-04-16 08:44:16
尝试使用getline(cin,uni)。cin本身只读到第一个空格。此外,find()函数返回您搜索的字符串的位置。您可能也希望对gold使用substr()函数。
编辑:我相信您的意思是在find()函数括号外写'+1‘和'-1’,以获得空格前后的位置。这也可能导致错误。
https://stackoverflow.com/questions/67121824
复制相似问题