【问题标题】:C++ Hello World Tutorial ErrorC++ Hello World 教程错误
【发布时间】:2014-02-06 18:08:53
【问题描述】:

我通过遵循书中的示例来学习 C++,在输入并仔细检查后,我不断收到错误消息。我不知道出了什么问题。如果重要的话,我正在使用 Visual C++ 2010。

#include <iostream>
using namespace std;

int main()
{
// Prompt the user for data 
cout << "Please enter two words:" << endl;

//Read in the values
string b, c;
cin >> b >> c;

// Give feedback
cout << "I understood: "
     << b << ", and "
     << c << endl;

// NOw, lets's read a whole line of text as a single entity
cout << "Now, type in a whole line of text, "
     << "with as many blanks as you want:"
     << endl;

//getline() is a function; we'll talk more about them in Part3 
string wholeLine;
getline( cin, wholeLine );

//In the cout statement below, remember that \"
// is an escape sequence!
cout << "I understood: \"" << wholeLine << "\"" << endl;

// And we're done! 
return 0;
}

有四个错误。 错误代码是:

错误 1 错误 C2678: 二进制 '>>' : 未找到采用 'std::istream' 类型左侧操作数的运算符(或没有可接受的转换) i:\ helloworld.cpp 11

错误 2 错误 C2679: 二进制 '

错误 3 错误 C3861: 'getline': identifier not found i:\helloworld.cpp 25

错误 4 错误 C2679: 二进制 '

【问题讨论】:

  • 你是否加入了stdafx.h
  • 我最好的猜测是你必须包含 stdio.h 或 stdafx.h 或其他东西。显然,iostream 中没有包含预期的内容。
  • #include &lt;string&gt; 绝对是必需的。没有它,您就没有正确的 getline() 声明。
  • 不只是getline(),如果不包含string 标头,您也不能使用string 类。
  • 所以应该...使用命名空间std;正在使用命名空间 stdafx.h

标签: c++


【解决方案1】:

string 缺少 #include &lt;string&gt;

【讨论】:

  • 就是这样。 &lt;string&gt; 定义了它的运算符 &lt;&lt;&gt;&gt;
  • 谢谢,这就是问题所在。我逐字逐句地按照书中的内容进行操作,但没有显示这一点。我想我最好找一本新书来使用。
  • @user3280763 这本书是什么?
  • @user3280763:看看The Definitive C++ Book Guide and List
  • @Jatin K&R(以及早期的 Stroustrup)是优秀的书籍,但它们并不针对初学者。 Programming: Principles and Practice using C++ 确实;它是为对编程以及如何编写程序一无所知的人设计的,它解决的不仅仅是纯 C++ 问题。
【解决方案2】:

正如 Wesley 已经说过的,确保您已包含该库。

另外,在同一程序中使用 getline()cin 时要非常小心。一个可以影响另一个,你会得到意想不到的结果。为了安全起见,我发现在使用 cin 之后使用 cin.ignore() 和使用 getline 之前使用 before 很有用。干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    相关资源
    最近更新 更多