为什么我不能使用 cout 在 C++ 中打印字符串值数组?

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

本文关键字:打印 字符串 数组 C++ 不能 cout 为什么      更新时间:2023-10-16

这是我正在编写的一个非常简单的程序的代码片段。我是C++的新手,但有Java背景,所以我可能对打印值的工作方式有先入为主的看法。我的问题是当我做这行:

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

我得到一条错误消息,说操作数与<lt;。基本上它是说我不能做cout<lt;垂直线[i]。

为什么会发生这种情况?

这是代码:

#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;
}

尝试包含<string>,应该足够

您必须包含标头<string>,该标头包含类别std::basic_string的定义,包括std::string

正是在这个标头中定义了operator <<

还要考虑使用类std::map代替数组。对于示例

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

如果不编译代码,则在初始值设定项列表中显式指定std::pair。例如

{ std::pair<std::string, int>( "AB", 0 ), std::pair<std::string, int>( "AC", 0 ), ...}