I need to read a number of unsigned character from the input(ASCII value>127).
SO i used-
unsigned char S[102];
but when i take input like this-
gets(S);
compiler show error:
error: invalid conversion from
‘unsigned char*’ to ‘char*’
So my question is how read unsigned character array using gets() or any other function exist.
First, you should never use
gets. It cannot be used safely under any circumstances. My comment may have been a bit hyperbolic for humorous effect, but the point still stands.The function you should use instead of
getsisfgets.fgetstakes aFILE *pointer (but you’ll probably just want to passstdin) and a maximum length, so it knows not to overflow your buffer. Unlikegets,fgetsisn’t guaranteed to read in an entire line – the line might be too big for your buffer to hold. You can, however, easily recover from this and write code to correctly process the input in a variety of ways (whereas withgetsyou just have to hope your buffer is long enough, and if it’s not, who knows what will happen.)I’m a little unclear on what kind of data you intend to read. If it’s text,
fgetsis probably what you’re looking for. It still takes achar *, so to make this work you’ll need to castSto achar *when you pass it to the function. Normally casts are a bad thing, especially casts from signed to unsigned types, but in this case nothing bad will (likely) happen.If you’re actually reading binary data into your unsigned array, you should look into
fread. Unlikefgetsit takes avoid *to accommodate whatever kind of data you need to read, so no cast will be necessary. Note thatfreadreads chunks rather than lines, so if you’re wanting textual input you should look elsewhere – it won’t try to read an entire line, nor will it stop reading into a buffer when it sees a line ending.