1

Ok so i started coding on c++ today and i got a problem, i wrote a code that ak you your name and your surname and then it write "Welcome name surname, enjoy my program", i wrote a getline (cin, name) and a getline (cin, surname) so i can insert two words on surname but when it says Welcome name surname there's only one word.

#include <string>
#include <cmath>
using namespace std;

//add #include <string> to use string variable
//add #include <cmath> to use math functions

int main() {

//your name and surname

    string name, surname;

    cout << "Insert your name \n";
    getline (cin, name);
    cin >> name;

    cout << "Insert your surname \n";
    getline (cin, surname);
    cin >> surname;

    // cout is "Welcome Name Surname, enjoy my program :)"

    cout << "Welcome " << name + " " + surname;
    getline(cout, surname);

    cout << ", enjoy my program :)";

    // use getline (cin, name,); to insert more words on cin

    return 0;

}

What do i have to do

why does it show only a word and not 2?

JvstAlf
  • 75
  • 8
  • 2
    It seems you should remove `cin >> name;` and `cin >> surname;`. – MikeCAT Nov 18 '20 at 15:18
  • 1
    Never mix `getline` and `cin >>` unless you expect trouble... – Serge Ballesta Nov 18 '20 at 15:21
  • The `getline()` calls should suffice to read the `name` and `surname`. Get rid of the lines with the ">>" operator and see how it goes. – Logicrat Nov 18 '20 at 15:23
  • 1
    @SergeBallesta there is nothing wrong with mixing `getline()` and `>>`, you just have to pay attention to what you are reading with each one, and make sure the stream is in a correct state when switching between them. – Remy Lebeau Nov 18 '20 at 15:33
  • @RemyLebeau You are right, of course. And I have already had to mix line oriented and stream oriented input in C++ or C. But IMHO it is a pitfall for beginners, so my advice to avoid it. (I have upvoted your comment to balance the +1 on mine) – Serge Ballesta Nov 18 '20 at 15:39
  • @MikeCAT that has no sense, i have to insert a name that get to variable naem and a surname that get to variable surname – JvstAlf Nov 18 '20 at 16:19
  • @JvstAlf Actually, getline is getting input from a string until it meets a newline ```'\n'```. You don't need ```cin``` after ```getline```. – justANewbie Nov 19 '20 at 08:42
  • @justANewbie with two question if theres no cin after the first it tells you Insert your name Insert your surname so theres i just added cin >> name after name and then on surname you can write more than 1 word – JvstAlf Nov 20 '20 at 09:04

0 Answers0