Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use cout to print an array of string values in C++? [duplicate]

Tags:

c++

arrays

cout

This is a code snippet from a pretty simple program I am writing. I am fairly new to C++, but have background in Java, so I may have preconceptions as to how printing values should work. My problem is when I do this line:

cout << "Please enter the weight for edge " << verticies[i] << endl;

I get an error message saying that the operands do not match the designated operator for <<. Basically it is saying I can't do cout << verticies[i].

Why does this happen?

Here is the code:

#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    string verticies[6] = { "AB", "AC", "AD", "BC", "BD", "CD" };
    int edges[6];

    for (int i = 0; i < 6; i++)
    {
        cout << "Please enter the weight for edge " << verticies[i] << endl;
    }

    system("PAUSE");

    return 0;
}
like image 893
Jordando Avatar asked Dec 12 '22 06:12

Jordando


2 Answers

Try including <string>, should be enough

like image 118
Ryp Avatar answered Apr 29 '23 06:04

Ryp


You have to include header <string> that contains the definition of the class std::basic_string including std::string

It is this header where the operator << is defined.

Also consider to use class std::map insted of the arrays. For exmple

std::map<std::string, int> verticies = 
{ 
   { "AB", 0 }, { "AC", 0 }, { "AD", 0 }, { "BC", 0 }, { "BD", 0 }, { "CD", 0 } 
};

If the code will not be compiled then explicitly specify std::pair in the initializer list. For example

{ std::pair<std::string, int>( "AB", 0 ), std::pair<std::string, int>( "AC", 0 ), ...}
like image 27
Vlad from Moscow Avatar answered Apr 29 '23 05:04

Vlad from Moscow