2

I have tried most of the string and char format types and they are not working and I have no Idea why. Here is my code :

#include <iostream>
#include <stdio.h>

using namespace std;
int main(int argc, const char * argv[])
{

    // insert code here...
    string string2;
    string string;

    cout << "Hello, World!\n";
    printf("Hi my name is Josh %s\n",string2);
    scanf("%s",&string);
    printf("hi %s",string);
}
3
  • scanf's %s format specifier requires a matching character array parameter, not a std::string. Commented Feb 12, 2014 at 0:54
  • Mixing of C and CPP style is not good idea in general. As it is mentioned already you should std::cin. If you are reading a string like 'Josh Surname' you may consider cin.getline(). If you really want to use scanf then consider sscanf instead. Commented Feb 12, 2014 at 1:02
  • Use std::getline(std::cin, string2); Commented Feb 12, 2014 at 2:22

2 Answers 2

4

What you're showing (scanf("%s",&string);) doesn't work (and never could, by e.g. giving different format specifiers)!

scanf() used with the %s format specifier requires a corresponding char* pointer referencing a raw char[] array to receive the read data in the parameter list. The std::string pointer you're passing in your example, doesn't provide automatic casting to the referred std::string instances internally managed char[] buffer that way though.

You could try to use &string.front() instead, but I wouldn't really recommend that, unless you're very sure what you're doing.

For you should better use std::cin and
std::istream& operator>>(std::istream&, const std::string&) instead:

std::cout << "Put in string value:" << std::endl;
std::string input;
std::cin >> input;

( isn't relevant for your question BTW!)

Sign up to request clarification or add additional context in comments.

Comments

0

You shouldn't mix std::cout with ::printf. Prefer to use the C++ Standard IO library over C functions from stdio.

Your code should look a little like this:

#include <iostream>

int main()
{
    std::string string2;
    std::string other_string;

    std::cout << "Hello, World!\n";
    std::cout << "Hi my name is Josh " <<  string2 << '\n';
    std::cin >> other_string;
    std::cout << "hi " << other_string;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.