I need to read input from user. The input value may be string type or int type.
If the value is int then the program insert the value into my object.
Else if the value is string then it should check the value of that string, if it’s “end” then the program ends.
Halda h; //my object
string t;
int tint;
bool end=false;
while(end!=true)
{
if(scanf("%d",&tint)==1)
{
h.insert(tint);
}
else if(scanf("%s",t)==1)
{
if(t=="end")
end=true;
else if(t=="next")
if(h.empty()==false)
printf("%d\n",h.pop());
else
printf("-1\n");
}
}
The problem is that scanning string doesn’t seem to work properly.
I’ve tried to change it to: if(cin>>t) and it worked well.
I need to get it work with scanf.
The specifier
%sin thescanf()format expects achar*, not astd::string.From C11 Standard (C++ Standard refers to it about the C standard library):
Anyway, here there’s is no real reason to prefer the C way, use C++ facilities. And when you use the C library, use safe functions that only reads characters up to a given limit (just like
fgets, orscanfwith a width specifier), otherwise you could have overflow, that leads again to undefined behavior, and some errors if you’re luck.