scanf , printf

the reference says the %s should be a string type arguement but when i implemented it the compilers gave me a warning that's a char and it really only reads chars

1
2
3
  	string x;
	scanf("%s",&x);
	printf("%s",&x);



any thoughts ?
string x is C++
scanf/printf are C

First decide which language you are using, and then be consistent.

However, since this is a C++site, how about
1
2
3
    string x;
    cin >> x;
    cout << x;

oh .. then why it's in the cplusplus reference ?
The reason im using scanf is that it omit spaces so basically it saves me some time of coding
oh .. then why it's in the cplusplus reference ?

C is still part of C++ that's probably the reason.

If you really need to use scanf and a string, here's a way to do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <cstdio>

int main()
{
  // Just a proof of concept - not really advisable to do

  std::string buffer(10, ' ');
  printf("Your input: ");
  scanf("%9s", &buffer[0]);
  printf("\n%s", buffer.c_str());

  system("pause");
  return 0;
}
Last edited on
 
C is still part of C++ that's probably the reason.  


so where did i go wrong , i must have missed something :\ .. why %s reads only a char ?
Have a look at the post above yours - probably you didn't see my edit.
Cool so basically %9s iterate over the string which is basically an array of chars .. thanks was a big deal of help ^^
Last edited on
Topic archived. No new replies allowed.