You are not logged in. Please login at www.codechef.com to post your questions!

×

Help with Run-time error using map and printf C++

Why does this code has a run-time error?

#include <cstdio>
#include <map>
#include <string>
#include <iostream>

using namespace std;
map <int, string> A;
map <int, string>::iterator it;

int main(){
    A[5]="yes";
    A[7]="no";
    it=A.lower_bound(5);
    cout<<(*it).second<<endl;    // No problem
    printf("%s\n",(*it).second); // Run-time error
    return 0;
}

Thanks!

asked 07 Nov '12, 05:56

dtalamas24's gravatar image

6★dtalamas24
967814
accept rate: 20%

reverted 08 Nov '12, 21:29

vinayak%20garg's gravatar image

4★vinayak garg
3.7k113249

1

So we have the answer, but not the question... What was it ?

(08 Nov '12, 03:30) rxitr0★

This is because printf("%s") expects a C-style string, not std::string

To fix it

  1. Use cout as it is much safer than printf, and can handle your own types (if you have overloaded operator<< for std::ostream)
  2. Or if you want to do it using printf, you can do A[5].c_str() to obtain C-style string.

    printf("%s", (*it).second.c_str()); //works

link

answered 07 Nov '12, 14:19

vinayak%20garg's gravatar image

4★vinayak garg
3.7k113249
accept rate: 18%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×1,912
×643
×278
×61
×32

question asked: 07 Nov '12, 05:56

question was seen: 5,510 times

last updated: 08 Nov '12, 21:29