why printf and scanf do not work when we use statements like this-
pair < int, string> f[10001];
scanf("%s %d",f[i].second,&f[i].first);//where 0<=i<=10000
but cin and cout works
You’re missing a very basic thing about strings in C/C++.
Not only pair, but even if you do this, you will get a Seg Fault.
string s;
int p;
scanf("%s %d", &s, &p);
cout<<p<<" "<<s<<"\n";
Whereas, writing this clears the Seg Fault
char s[10]; //or whatever size you need
I hope you find that error by yourself now.
Clarification: scanf()
expects C strings. You have two choices now. Either use cin
or if you want to use scanf
only, then use a temporary string (a C string) to take input and then copy that to f[i].second
@bugkiller has answered your question perfectly. However, I believe that you are avoiding cin and cout because they are said to be slow. If that is the case, you can write the following line as the first line in your main function to speed up cin and cout.
ios_base::sync_with_stdio(false); cin.tie(0);
e.g.
int main() { ios_base::sync_with_stdio(false); cin.tie(0); // rest of your code return 0; }
This doesn’t have to be the first line in main(). It just has to be executed before any input or output by your program. If you use this, then you MUST NOT use scanf or printf in the same program. You then have to use cin and cout throughout the whole program.
To understand why & how this speeds up cin/cout and why you must not use scanf/printf when you are using this, read: http://pointer-overloading.blogspot.in/2013/09/c-why-is-scanf-faster-than-cin.html
To understand cin.tie(0), read: http://www.cplusplus.com/reference/iostream/cin/
So, cout’s buffer is flushed before each i/o operation is performed on cin. cin.tie(0) prevents this.
thanks for sharing!!!
thanks for sharing!!!
@rudra_sarraf >> If you were satisfied with the answer you can accept the answer by clicking on the tick mark so that we can close the question.