简单的C++程序使用wstrings和cout无法编译

3

我正在使用Visual Studio 2012构建这个简单的C++程序:

#include <stdafx.h>

#include <string>
#include <iostream>

int main()
{
    std::wcout << "Hello World...";

    std::string input_data;

    std::string output_data("Hello. Please type your name");

    std::wcout << output_data;
    std::wcin >> input_data;

    std::wcout << "Your name is " << input_data;

    return 0;
}

我无法编译。出现以下错误:

error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::wistream' (or there is no acceptable conversion)

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

IntelliSense: no operator "<<" matches these operands
            operand types are: std::basic_ostream<wchar_t, std::char_traits<wchar_t>> << std::string    

IntelliSense: no operator "<<" matches these operands
            operand types are: std::wostream << std::string

IntelliSense: no operator ">>" matches these operands
            operand types are: std::wistream >> std::string

有人可以帮我修复这个问题吗?
2个回答

8

您应该尝试将所有std::string替换为std::wstring,或将所有wcin/wcout替换为cin/cout...(在第一种情况下,像L"aaa"这样的字符串前缀)。例如,以下代码可以完美运行:

#include <string>
#include <iostream>

int main()
{
    std::wcout << L"Hello World...";

    std::wstring input_data;

    std::wstring output_data(L"Hello. Please type your name");

    std::wcout << output_data;
    std::wcin >> input_data;

    std::wcout << L"Your name is " << input_data;

    return 0;
}

清晰简洁...太好了!谢谢帮忙...两种方式都可以正常工作。 - Mendes

0

或者,您可以将所有内容切换为窄字符串:

#include <string>
#include <iostream>

int main()
{
    std::cout << "Hello World...";

    std::string input_data;

    std::string output_data("Hello. Please type your name");

    std::cout << output_data;
    std::cin >> input_data;

    std::cout << "Your name is " << input_data;

    return 0;
}

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