开发者

question on struct in c++

开发者 https://www.devze.com 2023-01-06 09:34 出处:网络
I have the following code #include <iostream> 开发者_StackOverflow#include<string> #include <sstream>

I have the following code

#include <iostream>
开发者_StackOverflow#include<string>
#include <sstream>
using namespace std;
struct product{
    int weight;
    float price;
};
int main(){
    string  mystr;
    product  prod;
    product *pointer;
    pointer=&prod;
    getline(cin,pointer->price);
    return 0;
}

but it shows me the mistake

no instance of overloaded function "getline" matches argument list

What is the mistake?


The mistake is that you are trying to read a line of text into a float. Reading in an entire line requires that you read into a string. If you just want to read in a float from input, simply write:

cin >> pointer->price;

Which will read input up to the next whitespace and attempt to interpret it as a float.


The second argument to getline is supposed to be a reference to a string, not a float as you've used.

Or the other overload of getline you can use takes in a char* and a streamsize. Either way, the arguments you've specified do not match any overload of getline, and that is why you received the error you described.


The mistake is that getline returns string, not float.

string str;
getline(cin, str);
pointer->price = atof(str.c_str());
0

精彩评论

暂无评论...
验证码 换一张
取 消