[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 207
  • Last Modified:

Finding the argument

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

0
sidwelle
Asked:
sidwelle
  • 2
  • 2
2 Solutions
 
evilrixSenior Software Engineer (Avast)Commented:
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.
0
 
Daniel WilsonCommented:
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());
0
 
Daniel WilsonCommented:
You beat me, evil!
0
 
evilrixSenior Software Engineer (Avast)Commented:
Heh. Typing on a BB too :)
0
 
sidwelleAuthor Commented:
I appreciate everyone that answered.  
I knew I was throwing softballs, but I am outside of what my book covers.

Thanks
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now