1

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;
}
Shawn Brar
  • 337
  • 1
  • 9
  • Is `std::cin` still `.good()`? Can you do error handling like `if (std::getline(std::cin, name, ';') {...} else { std::cout << "Whoopsie, something bad\n" }` – sehe Jul 06 '20 at 01:23
  • 1
    Can you show the `main` version as well? – cigien Jul 06 '20 at 01:27
  • 2
    Chances are something is going wrong earlier. Consider a [mcve]. – Retired Ninja Jul 06 '20 at 01:38
  • 1
    My educated guess would be, this is a duplicate of [this question](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Igor Tandetnik Jul 06 '20 at 03:09
  • You shouldn't put functions in the header -- they go in the source file, you put a prototype in the header... (that doesn't explain your issue -- but that is a good place to start) – David C. Rankin Jul 06 '20 at 05:08
  • Why do you pass `b` by value? – Dmitry Kuzminov Jul 06 '20 at 05:28
  • "t does not asks for user input " maybe you did not flush the cout stream. A '\n' did not flush, you may use std::endl instead! – Klaus Jul 06 '20 at 07:07

1 Answers1

1

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.

darune
  • 9,436
  • 1
  • 16
  • 47