0

I'm not very experienced with c++, and I'm having trouble w/a program I'm making to learn some string functions. I've tried troubleshooting via writing other programs to test the functions individually.

Expected behavior: It determines a name before the " ", and an integer after.

Demonstrated behavior: Returns w/a blank name, and a 0.

My platform is 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;
}
John333
  • 3
  • 2
  • 1
    `cin >> uni;` will only read until the first whitespace (and overwrites the existing content). But you don't even need this, the string already contains test data. – Lukas-T Apr 16 '21 at 08:36
  • Another problem: What are `" "-1` and `" "+1` supposed to do? Tha invokes pointer arithmetic yielding an invalid pointer and one that points to `'\0'` respectively. Not sure what you intend to do there so it's hard to find an asnwer. – Lukas-T Apr 16 '21 at 08:39

1 Answers1

0

Try using getline(cin, uni). cin on its own only reads until the first space. Also, the find() function returns the position of the string you search for. You might want to use the substr() function for gold too.

Edit: I believe you meant to write the '+1' and '-1' outside the find() function brackets to get the position before and after the space. That may be causing the error as well.