Cannot read string with space by using getline

1
2
3
4
5
void Product::Input() {
	SetName();
	SetProductionYear();
	SetOriginalPrice();
}


1
2
3
4
5
void Product::SetName()
{
	cout << "Ten san pham: ";
	std::getline(std::cin,name_);//it cannot receive my input!
};


1
2
3
4
5
void Product::SetOriginalPrice()
{
	cout << "Gia nhap: ";
	cin >> original_price_;
}


1
2
3
4
5
void Product::SetProductionYear()
{
	cout << "Nam san xuat: ";
	cin >> production_year_;
}


Did I understand something wrong here?
Last edited on
#uouo99

I couldn't know how to set condition to break that loop since I try to set pointer for the name_ parameter but the problem is I don't know the length of it to set the condition
cin + getline is bad, google it.
std::getline (not to be confused with std::cin.getline) expects a reference to an std::string as its second argument. If name_ is a pointer to some buffer, that's not going to work (and it probably should be an std::string anyway).

I hope that's helpful, because otherwise there isn't enough information to give you more specific advice.

-Albatross
You should be able to read the string with the std::getline function. Be a
little more specific. What do you mean it isn't receiving your input? Is the
line skipping, or can you enter in the name and it doesn't have any value?

Consider the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>

int main() {
  std::string myString0;
  std::string myString1;

  std::cin >> myString0;

  /* This getline will "skip" and the value of myString1 will be a newline.
   * Why? Because the previous input was a std::cin and that will add a newline
   * to the input stream. If you use getline next, the string will be set to an
   * end line value. 
   *
   * To fix this "getline skipping", you can put a std::cin.ignore() after the
   * std::cin statement so the code becomes:
   *
   * std::cin >> myString0;
   * std::cin.ignore();
   * std::getline(std::cin, myString1); // line isn't skipped, and string is
   *                                    // read
   * */

  std::getline(std::cin, myString1);

  return 0;
}

Thanks you guys it actually worked perfectly like what #fiji885 said. I just need to write std::cin.ignore(); and it did not skip anymore.
Its like this
1
2
3
4
5
6
void Product::SetName()
{
	cout << "Ten san pham: ";
	std::cin.ignore();//this solved all the problem!!
	std::getline(std::cin, name_);
}

-PoorBoiz-
Last edited on
Topic archived. No new replies allowed.