简体   繁体   English

C ++中的结构问题

[英]question on struct in c++

I have the following code 我有以下代码

#include <iostream>
#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 没有重载函数“ getline”的实例与参数列表匹配

What is the mistake? 怎么了

The mistake is that you are trying to read a line of text into a float . 错误是您试图将一行文本读入一个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 . 它将读取输入直到下一个空格,并尝试将其解释为float

The second argument to getline is supposed to be a reference to a string, not a float as you've used. getline的第二个参数应该是对字符串的引用,而不是您所使用的float。

Or the other overload of getline you can use takes in a char* and a streamsize . 否则,您可以使用getline另一个重载方法获取char*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. 无论哪种方式,您指定的参数都不匹配getline任何重载,这就是为什么您收到所描述的错误的原因。

The mistake is that getline returns string, not float. 错误是getline返回字符串,而不是float。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM