Finding the argument

Posted on 2011-10-24
Last Modified: 2012-05-12
In the attached code, why dose 'cout' work and the printf("%s", MyVal)   get a compiler error ?

int main(int argc, char* argv[])

	for (int i = 1; i < argc; i++)
		//printf(argv[i]); printf("\n");
		printf( "arg %d: '%s'\n", i, argv[i] );

		//if (strcmp(argv[i], "/s:")==0)
		if (strncmp(argv[i], "/s:", 3) ==0)
			printf("Found It, the arg is :");
			string str = argv[i];
			string MyVal = str.substr(4);
			//cout << MyVal;    //this works.
			printf("%s", MyVal); //this fails.



Open in new window

Question by:sidwelle
    LVL 39

    Accepted Solution

    Printf is a C function, it knows nothing about a C++ string: use MyVal.c_str() as this returns a char pointer that printf does understand.
    LVL 32

    Assisted Solution

    by:Daniel Wilson
    If I'm not mistaken, printf wants a char*, not a string.

    Now, a string should have a method that will provide a char* ... depending on the implementation it could well be .c_str()

    printf("%s", MyVal.c_str());
    LVL 32

    Expert Comment

    by:Daniel Wilson
    You beat me, evil!
    LVL 39

    Expert Comment

    Heh. Typing on a BB too :)

    Author Closing Comment

    I appreciate everyone that answered.  
    I knew I was throwing softballs, but I am outside of what my book covers.


    Featured Post

    Courses: Start Training Online With Pros, Today

    Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

    Join & Write a Comment

    Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
    Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
    The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
    In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now