Shawn Brar
Shawn Brar

Reputation: 1420

std::getline does not works inside a function

I have the following function:-

void my_func(std::string b){
        std::string name;
        std::cout << "Please enter the name\n";
        std::getline(std::cin, name, ',')
        b = name;
        std::cout << "b = " << b << "\n";
}

The problem with this function is when I put it in a header file, the std::getline(std::cin, name, ',') line of the code does not runs ie it does not asks for user input but proceeds printing b. I cannot understand why this is happening.

If I write lines 2 to 6 of my above code in main, it works. But if I put these lines inside a function, it does not works.

#include <iostream>
#include <string>
int main(){
        std::string name, b;
        std::cout << "Please enter the name\n";
        std::getline(std::cin, name, ',')
        b = name;
        std::cout << "b = " << b << "\n";
        return 0;
}

Upvotes: 2

Views: 226

Answers (1)

darune
darune

Reputation: 10962

You are modifying a copy of the parameter:

Instead of:

void my_func(std::string b){ //<--semantic meaning "take a copy of b"

Change To:

std::string my_func() // <-- returning a std::string by value
{
  std::string b;
  //...
  return b;
}

Note that "return by reference" is also an option, but it's semanticly more complicated (some might say a lot more), therefore shouldn't be the first choice for a solution. However I show it here because you still need to know this concept and references overall:

void my_func(std::string& b){ //<-a reference to a string

Additionally, const references (eg. const std::string& b) are a common way of passing parameters when a copy of an object could be expensive.

Upvotes: 2

Related Questions