cout to printf

Hi, I'm a noob (bite me!) and I'm doing a C++ exercise. How do I write this in printf()?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>  //  Import the input-output library
#include <string>
using namespace std;  //  allows us to write cout
                    //  instead of std::cout
int main()
{
	cout << "Enter a name:" << endl;
	string name; 
		cin >> name;
		cout << "Enter an age:" << endl;
		int age;
	cin >> age;
	cout << "Well, " << name << " you are " << age << " years old." << endl;
}
That has me javascript:editbox1.editSend()spinning in millions of circles....
And scanf (to replace cin)

http://www.cplusplus.com/reference/cstdio/scanf/

If you just check out the examples (rather than try to get all the info in the tables) in these two articles you should be able to translate your C++ code into C easily enough!?

Andy
Last edited on

Good catch Andy, forgot to include cin->scanf link :)
I've been learning from this book:

http://www.amazon.com/Learning-C-Creating-Games-UE4-ebook/dp/B00U01QQV6/ref=pd_sim_351_9?ie=UTF8&refRID=166QVM9125BNQYKRVZT3

It talks about printffh, but I havn't seen scanf yet I think I get it though.

printf ("Enter a name: ");
scanff ("%10s");
printf ("Enter an age: ");
scanf ("%d");
printf ("Well, %s, you are %d years old. \n" );
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <cstdio> // printf 
#include <iostream> // cin

int main()
{
	printf( "Enter a name:\n" );
	char name[100]; 
		std::cin >> name;
		printf( "Enter an age: " );
		int age;
	std::cin >> age;
	printf( "Well, %s you are %d years old.\n", name,  age);
}


This shows how printf can substitute for cout. scanf is a similar proposition. Note that name must be a C-string (character array)
Line 7 limits a name to 100 characters, right?
It makes the name array 100 characters long.

It does NOT limit the amount of characters you can attempt to write though, so you can easily mess things up by writing too many characters.
It makes the name array 100 characters long.

It uses up 100 characters worth of memory, regardless of the length of the name.

Of course that is just a nit pick of mine concerning a different reason to avoid char arrays.
closed account (48T7M4Gy)
Line 7 limits a name to 100 characters, right?


Sure does, in this case - make it 5, 1000 or whatever you want/need! The important thing to know is printf requires a C-string.
Line 7 limits a name to 100 characters, right?

Actually, it limits the (safe) maximum length of the name to 99 chars; you need to set aside one element in the array for the null terminator.

but I havn't seen scanf yet

Did you check out the examples in the reference entires that Softrix and I pointer you at? They include pretty much everything you need to sort out your code.

Andy
Last edited on
Yeah, I did. Just don't have a firm grasp yet.

Thanks, guys.
Topic archived. No new replies allowed.