开发者

How to read unsigned character array using gets()?

开发者 https://www.devze.com 2023-03-09 09:09 出处:网络
I need to read a number of unsigned character from the input(ASCII value>127). SO i used- unsigned char S[102];

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 func开发者_C百科tion 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 gets is fgets. fgets takes a FILE * pointer (but you'll probably just want to pass stdin) and a maximum length, so it knows not to overflow your buffer. Unlike gets, fgets isn'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 with gets you 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, fgets is probably what you're looking for. It still takes a char *, so to make this work you'll need to cast S to a char * 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. Unlike fgets it takes a void * to accommodate whatever kind of data you need to read, so no cast will be necessary. Note that fread reads 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.


Instead of gets you can use:

  • fgets (s, MAX_BUFFER, stdin);
  • scanf ("%[^\n]%*c", s);

Both will work when taking ASCII characters with values greater than 127 like : .±┼┤.␤▒⎽␤ .␍≤┼⎽≤└ .␍≤┼⎽├⎼ .±┼┤.┴␊⎼⎽␋⎺┼ .±┼┤.┴␊⎼⎽␋

gets will also do the thing. You do not need to pass your array as unsigned char *.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号