Home > Net >  no match for ‘operator>> help ;(
no match for ‘operator>> help ;(

Time:01-12

I've just started in C , and I have this problem that I don't know how to solve. When I try to compile my little program, it just doesn't work for me.

The error:

no match for ‘operator>>’ (operand types are ‘std::istream’ {aka ‘std::basic_istream’} and ‘TDatosP’ {aka ‘std::__cxx11::basic_string [100]’}) "

The main problem is here, I think --> cin >> list.data;

#include <iostream> 
#include <string> 

using namespace std; 

const unsigned MAXP = 100;
typedef string TDataP[MAXP]; 

struct TListP 
{ 
    unsigned np; 
    TDataP data;
};

int main() 
{ 
    TListP list; 

    cout << "Name: "; 
    cin >> list.np; 

    cout << "Data: "; 
    cin >> list.data; 

    return 0; 
}

CodePudding user response:

You introduced an alias for an array type

typedef string TDataP[MAXP];

A data member of this array type is also declared in structure TListP

struct TListP 
{ 
unsigned np; 
TDataP data; };

The compiler issues an error for this statement

cin >> list.data;

because the operator >> is not defined for such an array.

What you need is to use the operator >> for elements of the array in a loop.

For example

for ( auto &s : list.data )
{
    std::cin >> s;
}

Take into account that this prompt

cout << "Name: "; 

looks confusing for readers of the code when such a prompt is used to ask to enter an integer.

cin >> list.np; 

Maybe actually instead of the array of objects of the type std::string you mean a single object of the type std::string like

std::string data;

In this case you may write

cin >> list.data;

CodePudding user response:

Some changes alongside with comments

#include <iostream> 
#include <string> 

// It is usually recommended to avoid using `using namespace` in global scope. 
//It is ok in a small program like this one, but it doesn't really make much difference here.
// Anyway, just put it inside the main() and that'll do.

// You can use constexpr, 
// which also implies const in variable declarations
constexpr unsigned MAXP = 100;

// Since C  11 you can use `using` instead of old-style `typedef` 
// (and why would you learn pre-C  11 C   when there's C  20 and C  23 is on the way?)
using TDataP = std::string[MAXP];


struct TListP 
{ 
    unsigned np; 
    std::string data[MAXP]; // an array of strings
};

int main() 
{ 
    using namespace std;

    TListP list; 

    cout << "Name: "; 
    cin >> list.np; 

    cout << "Data: "; 
    // cin >> list.data; // this won't compile.
    // You'll need to iterate through the array and cin>> your string one by one. 

    return 0; 
}

So the problem here was that the operator>> doesn't know how to work with your type (you declared TDataP to be an array of std::strings) and needs to be overloaded for that purpose.

  •  Tags:  
  • Related