You are here:

C++/Basic question regarding C programing

Advertisement


Question
Hi!

I am a complete beginner in programing and I have a very basic question. I'm reading one of the tutorials on programing in C on the web. There is a small program(Conversion table from °F to °C) that I am supposed to change a bit. I'll paste the instructions, the original program and my final solution:

1) Original program:

#include <stdio.h>

int main()
{
   int a;
   a = 0;
   while (a <= 100)
   {
       printf("%4d degrees F = %4d degrees C\n",
           a, (a - 32) * 5 / 9);
       a = a + 10;
   }
   return 0;
}

2) Instructions:

Try changing the Fahrenheit-to-Celsius program so that it uses scanf to accept the starting, ending and increment value for the table from the user.

3) My solution:

#include <stdio.h>

int main()
{
   int a;
   a = 0;
   printf("Enter the amount in F to convert to C:");
   scanf_s("%d, &a");
   while (a <= 100)
   {
     printf("%4d degrees F = %4d degrees C\n",
           a, (a - 32) * 5 / 9);
       a = a + 10;
   }
   return 0;
}

Now, when I debug/build it in Visual c++ Express, the program reports no mistakes, but when I run it in Comand Prompt it crashes right after I enter "The amount of F..." What am I missing?

Thank you in advance for your answer!

Kind regards,

Simen

Answer
> scanf_s("%d, &a");

scanf_s is not part of the C standard library, it is a Micosoftism. Avoid it.

scanf takes a 'format_specifier' - a string specifying the type and format of the data to be read - as its first argument, and the address(es) of the variable(s) into which the data is to be read as the subsequent arguments.
See: http://www.cs.utah.edu/~zachary/ispmma/tutorials/io/io.html
http://www.codersource.net/c/c-miscellaneous/scanf.aspx  

For your specific program, change scanf_s("%d, &a"); to scanf( "%d", &a );

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

©2012 About.com, a part of The New York Times Company. All rights reserved.