September 6th, 2013, 01:26 AM
Code conversion Question
Hi I have the following C++ code and wanted to know if anyone could translate it in C for me. Thanks
int c, d, num, sum;
cout << “Enter a number -> ”;
cin >> num;
while (num > 20)
cout << “enter the first number -> ”;
cin >> c;
cout << “enter the second number -> ”;
cin >> d;
sum = c + d;
cout << “The sum of the numbers is -> ” << sum << endl;
num = num -1;
September 6th, 2013, 02:06 AM
have you tried doing it yourself??
September 6th, 2013, 10:17 AM
Replace cin with scanf. Replace cout with printf. The Web abounds with examples, including the man pages for both functions (IOW, RTFM). Keep in mind that you need to give scanf the address of the variable, while you only need to give printf the value.
September 6th, 2013, 11:04 AM
Hi I have tried doing it myself and the only part I need help with is how to do the while num> 15 and the last line num=num-1. How would I convert those lines into C?
September 6th, 2013, 11:43 AM
Again: Replace cin with scanf. Replace cout with printf.
Originally Posted by vcapp23
It's not a simple literal replacement, but rather use the scanf function for input and the printf function for output. Read their man pages.
Also -- and this is extremely important --, do not use a word processor to write your code! The compiler will not recognize the quotation marks that a word processor will insert and will issue errors for each quotation mark. We know this because somebody else had tried it before and that's what happened to him.
BTW, I just performed the conversion and it is rather straightforward, nothing at all tricky about it.
Last edited by dwise1_aol; September 6th, 2013 at 12:02 PM.
September 6th, 2013, 03:04 PM
Okay I did what you stated and this is what I got: It is pretty straightforward, but what do I do with the while num>20 line and the num=num-1? I ignored them in the code below.Can I just add it in there with the same syntax as C++?
int c, d, sum;
printf("Enter the first number\n");
printf("Enter the second number\n");
sum = c + d;
printf(" The sum of the numbers is = %d\n",sum);
September 6th, 2013, 03:49 PM
C++ is a superset of C. That means that C++ uses the same syntax as C except for features that C++ has which C does not (eg, classes). iostreams is just a class library that got added on for C++ (and is not supported by C). You could just as easily use C I/O functions in C++ and that is exactly what I do, since I find iostreams to be cumbersome and a stumble backwards towards Turbo Pascal.
So to convert your C++ code to C, all you needed to do was to convert the iostreams to stdio.
BTW, your scanf format string is wrong:
Why are you telling it to read in two integers when you're only giving it the address of one? And when the original iostream statement only read in one value?
And why are you asking this same exact question for Visual Basic? Smells like homework.