c++ - scanf problems involving string input and string comparison -
i have started working on scanf , printf in general, , in research , general screwing around have run problem in code multiple times decided make test program , have replicated error.
#include <string> #include <string.h> #include <stdio.h> int main(){ std::string name; std::string name2; printf("print donald or larry: "); scanf("%s",name); if(strcmp(name.c_str(), "donald") == 1){ printf("you entered donald"); goto stop; }else{ printf("you entered larry"); goto stop; } stop: return 0; } when attempt compile code throws me error coming line 10
error:
error: cannot pass objects of non-trivially-copyable type 'std::string {aka class std::basic_string<char>}' through '...'| source:
scanf("%s", name); i have tried both name.c_str , &name , both don't work, name.c_str makes if statement bug out , not work &name crashes altogether, although have found &<variable> works integers far.
what doing wrong?
if trying write c++ code use following
#include <iostream> using std::cout; using std::endl; using std::cin; #include <string> using std::string; int main(){ // declare string object std::string name; // output prompt , input cout << "print donald or larry: "; cin >> name; if (name == "donald") { cout << "you entered donald" << endl; } else if (name == "larry") { cout << "you entered larry" << endl; } return 0; } you doing things "wrong" in code above.
- scanf , printf c functions , should used cstrings not
stringobjects. if usingstd::string, programming in c++ , should use functionality provided c++ standard library header<iostream> - using
gotoin code bad idea.
Comments
Post a Comment