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

4

以下是我正在编写的相当简单的程序中的代码片段。虽然我有Java的背景,但我对C++还比较新手,因此可能会对打印值的方式有先入为主的看法。 我的问题是当我执行下面这行代码时:

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

我收到一个错误信息,说操作数与 << 指定的运算符不匹配。基本上是说我不能做 cout << verticies[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;
}

2
你有包含 <string> 吗? - Cameron
当询问这种问题时,错误的确切文本非常有帮助。 - Michael Kohne
1
摒弃 stdafx.h,对于小程序来说,预编译头文件并不值得麻烦。 - Thomas Matthews
2个回答

10

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


啊!非常感谢您的快速回复。这解决了问题。 - Jordando
请将此线程标记为已解决。 - Ryp

3

您需要包含头文件<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 ), ...}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接