[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: problem with a c code



On 26/04/2012 12:31, hector gonzalez wrote:
> good evening
> 
>     I have started working with geany a few days mostly because I was using
> Borland c++ 5.0 and that is because that is what my teachers use in college (I'm
> from venezuela), but the problem came when I was trying to capture strings with
> gets(), the program fails and I going to post in the message the code so you can
> see for yourself.
>

Hi Hector,

You're in the wrong list. This mailing list is for discussion of the Common
Language Infrastructure (also known as the .NET framework) in Debian.

But since you're here already, here's an answer. The offending code is:

cout<<"Sueldo: "; cin>>emp[i].sueldo; cout<<endl; followed by gets(emp[i].nombre);

When you key in the input for that field, e.g. 1.0, what you have keyed in is
"1.0\n". However, cin >> emp[i].sueldo; only reads in "1.0", leaving "\n" in the
input buffer.

gets() reads until the next \n, which results in an empty string.

There are two solutions to this:
1. Ignore the rest of the line:
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');

2. Read it line by line:
std::string buf;
getline (std::cin, buf);
std::istringstream(buf) >> emp[i].sueldo;

Also, Using gets() is dangerous as you'll get a buffer overflow if your user
keys in input that exceeds the length you've specified in your code. Since
you're using C++, you should use std::string and std::getline for reading in
whole lines, which is much safer.

> Note: if you don't understand spanish don't worry just input any string
> eventually you'll see the problem
> [...]

Note: If I wasn't feeling particularly patient, I would just ignore your
question after seeing this. You might like to explain your question in full the
next time you ask a question (and preferably in the correct place).

-- 
Kind regards,
Loong Jin

Attachment: signature.asc
Description: OpenPGP digital signature


Reply to: