473,657 Members | 2,436 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

scanf (yes/no) - doesn't work + deprecation errors scanf, fopen etc.

Hi,

Consider:
------------
char stringinput[64]

..bla. bla. bla.

do
{
printf("Write to result.txt (y/n)? ");
scanf("%s", stringinput);
}
while (writechar != 'y' || != 'n');
The compiler complaints. It says: error C2059: syntax error : '!='

Another problem is that MS VS 2005 keeps complaining about deprecated
commands such as:

1. warning C4996: 'fscanf' was declared deprecated..... ..: see
declaration of 'fscanf' - Message: 'This function or variable may be
unsafe. Consider using fscanf_s instead. To disable deprecation, use
_CRT_SECURE_NO_ DEPRECATE. See online help for details.'

2. warning C4996: 'scanf' was declared deprecated: see declaration of
'scanf'... Message: 'This function or variable may be unsafe. Consider
using scanf_s instead. To disable deprecation, use ...

3. warning C4996: 'fopen' was declared deprecated.... : see declaration
of 'fopen' Message: 'This function or variable may be unsafe. Consider
using fopen_s instead. To disable deprecation, use
_CRT_SECURE_NO_ DEPRECATE. See online help for details.'
How do I fix these problems? Sorry, but I'm not very experienced with C
programming.
Med venlig hilsen / Best regards
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 16 '06
185 17341
Barry Schwarz wrote:
-snip-
This should be :
while (writechar != 'y' || writechar != 'n');

While it is now syntactically correct, the expression will always
evaluate to true. Use &&, not ||.


Damn... Thanks...
Med venlig hilsen / Best regards
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 18 '06 #21
"Michael Mair" <Mi**********@i nvalid.invalid> skrev i en meddelelse
news:45******** ****@individual .net...
-snip-
Another thing: There is no equivalent to the run-time determination
of field width and precision for printf(). If you do not want to
have magic numbers you always have something like that:

#define STRINGIZE(S) #s
#define XSTR(S) STRINGIZE(S)

#define BUFSIZE 20

...
char buffer[BUFSIZE+1];
....
ret = sscanf("%" XSTR(BUFSIZE) "s", buffer);
....

Not really what I'd call flexible. And I am a friend of sscanf().


How about using getchar() like this for a yes/no test:

printf("Write to file result.txt (y/n)? ");
while ( tolower(writech ar = getchar() ) != 'y' && tolower(writech ar) != 'n')
{
if (writechar != '\n')
printf("Write to file result.txt (y/n)? ");
};

if (tolower(writec har) == 'j')
bla. bla. (write to file)
if no, then quit etc...
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 18 '06 #22
Broeisi a écrit :
This code will do what you want... __fpurge(stdin) ; // clear the stdin to strip off the previous newline char.


Bad avice. This function is not standard.

You should use fgets() with an array of 3 (at least) char...

--
A+

Emmanuel Delahaye
Feb 18 '06 #23
"Martin Joergensen" <un*********@sp am.jay.net> wrote in message
news:td******** ****@news.tdc.d k...
How about using getchar() like this for a yes/no test:
It would be better if you posted a fully compilable program. I assume you
included <ctype.h> and declared writechar as int. There are still some
problems with your implementation.
printf("Write to file result.txt (y/n)? ");
while ( tolower(writech ar = getchar() ) != 'y' && tolower(writech ar) != 'n') {
if (writechar != '\n')
printf("Write to file result.txt (y/n)? ");
};


You are not taking into account that a call to getchar() may return EOF
except for a character. This may happen if end of file is encountered or in
case of an error.

What happens if the user of your program types more than one character and
then presses <Enter>?
1) If the first character is one of those you are looking for
('y','n','Y','N '), the while loop exits and the rest of the typed characters
still reside in stdin. If you read the stdin later on, you will first read
those characters.
2) If the first character is not one of the expected ones, the message
printed in the body of your loop, will be printed repeatedly until all
characters in the stdin are consumed.
I do not think this is the behaviour you desire, so you should focus on
fixing these problems.
Feb 18 '06 #24
stathis gotsis wrote:
"Martin Joergensen" <un*********@sp am.jay.net> wrote in message
news:td******** ****@news.tdc.d k... -snip-
You are not taking into account that a call to getchar() may return EOF
except for a character. This may happen if end of file is encountered or in
case of an error.
EOF when I read from keyboard?
What happens if the user of your program types more than one character and
then presses <Enter>?
Yeah, I know it's a problem I'm trying to fix...
1) If the first character is one of those you are looking for
('y','n','Y','N '), the while loop exits and the rest of the typed characters
still reside in stdin. If you read the stdin later on, you will first read
those characters.
2) If the first character is not one of the expected ones, the message
printed in the body of your loop, will be printed repeatedly until all
characters in the stdin are consumed.
I do not think this is the behaviour you desire, so you should focus on
fixing these problems.


#include <stdio.h>
#include <ctype.h>

#define buffer_length 2

main()
{
char writechar[buffer_length];

writechar[0]='a'; // initialize it to something other than y/n

while ( tolower(writech ar[0] ) != 'y' && tolower(writech ar[0]) != 'n')
{
if (writechar[0] != '\n')
printf("Write to the file result.txt (y/n)? ");
fgets(writechar , buffer_length, stdin);
}

if (tolower(writec har[0]) == 'y')
printf("You typed \"y\"\n");
else if (tolower(writec har[0]) == 'n')
printf("You typed \"n\"\n");
}
Now, even though I made "#define buffer_length 2" I would expect that if
the user typed something like "asdfa", then the question wouldn't be
printed 5 times... But it is printed 5 times... Without having to
download any libraries or whatever, how to fix this final problem? I
assume the definition of writechar is ok (or should be it an array of
length 3)?
Med venlig hilsen / Best regards
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 18 '06 #25
Martin Jørgensen <un*********@sp am.jay.net> writes:
stathis gotsis wrote:
"Martin Joergensen" <un*********@sp am.jay.net> wrote in message
news:td******** ****@news.tdc.d k... -snip-
You are not taking into account that a call to getchar() may return EOF
except for a character. This may happen if end of file is encountered or in
case of an error.


EOF when I read from keyboard?


Yes, of course, typically triggered by control-D or control-Z.

[snip]
#include <stdio.h>
#include <ctype.h>

#define buffer_length 2

main()
{
char writechar[buffer_length];

writechar[0]='a'; // initialize it to something other than y/n

while ( tolower(writech ar[0] ) != 'y' && tolower(writech ar[0]) != 'n')
{
if (writechar[0] != '\n')
printf("Write to the file result.txt (y/n)? ");
fgets(writechar , buffer_length, stdin);
}

if (tolower(writec har[0]) == 'y')
printf("You typed \"y\"\n");
else if (tolower(writec har[0]) == 'n')
printf("You typed \"n\"\n");
}
Now, even though I made "#define buffer_length 2" I would expect that
if the user typed something like "asdfa", then the question wouldn't
be printed 5 times... But it is printed 5 times... Without having to
download any libraries or whatever, how to fix this final problem? I
assume the definition of writechar is ok (or should be it an array of
length 3)?


If fgets() tries to read a line longer than the specified length
(buffer_length) , the remainder of the line is left on the input
stream, to be read by the next call to fgets(). Repeated calls to
fgets() will read the entire line, a chunk at a time.

You probably don't want to examine every character on the input line,
just the first one. Or maybe you want to skip whitespace.

You can use fgets() with larger size argument to read the entire input
line into a string, then examine just the first character of the
string. If fgets() didn't read the entire line, the last character of
the string won't be a '\n' character; you can then discard the rest of
the line.

Or you can read a single character, check whether it's 'y' or 'n', and
then discard the rest of the line (up to the first '\n'). Decide what
you want to do on an empty input line (i.e., if the first character
you read is '\n'), and how you want to handle an EOF condition.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 18 '06 #26
"Martin Jørgensen" <un*********@sp am.jay.net> wrote in message
news:c2******** ****@news.tdc.d k...
stathis gotsis wrote:
"Martin Joergensen" <un*********@sp am.jay.net> wrote in message
news:td******** ****@news.tdc.d k... -snip-
You are not taking into account that a call to getchar() may return EOF
except for a character. This may happen if end of file is encountered or in case of an error.


EOF when I read from keyboard?


Yes, it is possible when you type something like CTRL-D or CTRL-Z(It is
CTRL-Z typed at the start of the input line on a windows dos console). Also,
getchar() may return EOF in case of an error, so you should consider
comparing the return value of getchar() to EOF too.
#include <stdio.h>
#include <ctype.h>

#define buffer_length 2

main()
{
char writechar[buffer_length];

writechar[0]='a'; // initialize it to something other than y/n

while ( tolower(writech ar[0] ) != 'y' && tolower(writech ar[0]) != 'n')
{
if (writechar[0] != '\n')
printf("Write to the file result.txt (y/n)? ");
fgets(writechar , buffer_length, stdin);
fgets() will read up to (buffer_length-1 = 1) characters, so the problem
remains unsolved. Even if you increase buffer_lenth, the user might input
long lines so that fgets() does not read all of the input. I think you
should stick with your previous implementation where you used getchar(). You
will just have to read the first character each time, then eat up rest of
the input until you reach the newline. In all cases, handle EOF.
}

if (tolower(writec har[0]) == 'y')
printf("You typed \"y\"\n");
else if (tolower(writec har[0]) == 'n')
printf("You typed \"n\"\n");
}


Feb 19 '06 #27
Martin Jørgensen schrieb:
stathis gotsis wrote:
"Martin Joergensen" <un*********@sp am.jay.net> wrote in message
news:td******** ****@news.tdc.d k...


-snip-
You are not taking into account that a call to getchar() may return EOF
except for a character. This may happen if end of file is encountered
or in
case of an error.


EOF when I read from keyboard?


As the others have not mentioned it: You can redirect a file
to stdin on many systems. I like to do that for C courses;
redirect stdin/stdout/stderr and let a bash script or batch
file check whether everything has been done correctly...

Interestingly, if I feed the elsethread (*) posted get_double
programme with an invalid file (containing only ".\n"), the
programme is caught in an endless loop as I forgot to break
the loop on file end and file error conditions... ;-)
This was not a problem for interactive input as the EOF
condition was given once and afterwards the loop could
continue, but in this case, we always get EOF. So much for
sufficient error handling.

<snip>
Cheers
Michael

(*) <45************ @individual.net >
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Feb 19 '06 #28
"stathis gotsis" <st***********@ hotmail.com> skrev i en meddelelse
news:dt******** **@ulysses.noc. ntua.gr...
-snip-
EOF when I read from keyboard?


Yes, it is possible when you type something like CTRL-D or CTRL-Z(It is
CTRL-Z typed at the start of the input line on a windows dos console).
Also,
getchar() may return EOF in case of an error, so you should consider
comparing the return value of getchar() to EOF too.


Ok, clear...
#include <stdio.h>
#include <ctype.h>

#define buffer_length 2

main()
{
char writechar[buffer_length];

writechar[0]='a'; // initialize it to something other than y/n

while ( tolower(writech ar[0] ) != 'y' && tolower(writech ar[0]) != 'n')
{
if (writechar[0] != '\n')
printf("Write to the file result.txt (y/n)? ");
fgets(writechar , buffer_length, stdin);


fgets() will read up to (buffer_length-1 = 1) characters, so the problem
remains unsolved. Even if you increase buffer_lenth, the user might input
long lines so that fgets() does not read all of the input. I think you
should stick with your previous implementation where you used getchar().
You
will just have to read the first character each time, then eat up rest of
the input until you reach the newline. In all cases, handle EOF.


Hmm. Okay, but I'm not really sure about how to discard the rest of the
line....... This program that was posted earlier had an error with the
__fpurge(stdin) - how do I modify it to work with standard C without
downloading any libraries or anything?:
#include <stdio.h>

int main(void)
{
char stringInput;

do
{
printf("\nWrite to result.txt (y/n)? ");
stringInput = getchar();
__fpurge(stdin) ; // clear the stdin to strip off the previous newline char.
}
while (stringInput != 'y' && stringInput != 'n');

printf("Thank you very much\n");

return 0;
}

Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 19 '06 #29
Martin Joergensen schrieb:
"stathis gotsis" <st***********@ hotmail.com> skrev i en meddelelse <snip!>
fgets() will read up to (buffer_length-1 = 1) characters, so the problem
remains unsolved. Even if you increase buffer_lenth, the user might input
long lines so that fgets() does not read all of the input. I think you
should stick with your previous implementation where you used getchar().
You
will just have to read the first character each time, then eat up rest of
the input until you reach the newline. In all cases, handle EOF.


Hmm. Okay, but I'm not really sure about how to discard the rest of the
line....... This program that was posted earlier had an error with the
__fpurge(stdin) - how do I modify it to work with standard C without
downloading any libraries or anything?:

#include <stdio.h>

int main(void)
{
char stringInput;

int tmp;
do
{
printf("\nWrite to result.txt (y/n)? ");
stringInput = getchar();
Hmmm, go back to the comp.lang.c FAQ and read it carefully.

getchar() returns int, where the characters are cast to
unsigned char and EOF is a negative int value.
Every character literal in C is of type int.
If you make stringInput type char you can miss EOF returns or
returns >= SCHAR_MAX.
__fpurge(stdin) ; // clear the stdin to strip off the previous newline char.
while (EOF != (tmp = getchar()))
if ('\n' == tmp)
break;
or
do {
tmp = getchar();
} while(EOF != tmp && '\n' != tmp);
}
while (stringInput != 'y' && stringInput != 'n');

printf("Thank you very much\n");

return 0;
}


Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Feb 19 '06 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1540
by: Juggernaut | last post by:
Hi I was trying to write a script to replace some text inside some tags. Lets say I had <tag stuff=stuff><tag stuff=otherstuff><another> I wanted it to find all the <tag and remove them. So I tried to write it so that it would go forward until it reached came. But when I tried that it would respond to another as single characters and not as the word.
11
2337
by: Savas Ates | last post by:
CREATE PROCEDURE st_deneme @userid numeric (18) ,@result numeric (18) output AS select * from users return "10" GO **************************** <!--METADATA TYPE="typelib" NAME="Microsoft ActiveX Data Objects 2.8 Library"
7
1656
by: Wen | last post by:
Hi everyone, ..After my first lesson, I have to create a asp page with: ..asp tag for time ..client script that runs at the server for date ..client script that runs at client and shows a messagebox These are my code, but it doenst work. Can someone help me? <html> <head> <title>18 Nov 2004 My first ASP page</title>
0
364
by: Daniel | last post by:
how to make sure a xsl document has valid xsl syntax? i tried loading it into an xml document but that doesnt show syntax errors inside attributes such as "foo/bar" vs "bar\foo"
13
1592
by: nigel.t | last post by:
Using linux <?php exec("/bin/tar -cvzf myfile.tgz /home/",$arrayout,$returnval); ?> or perhaps try it on your system and tell me if it does/doesnt and what your linux is? I've also tried
0
8395
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8310
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8826
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6166
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.