字符串的 Cout 给出了一个错误,并且很难获得一些见解帮助?

发布于 2024-12-14 12:41:03 字数 382 浏览 3 评论 0原文

我找不到这段代码中的错误,有人可以洞察我吗?我运行了调试,但错误是无法理解的。

#include "stdafx.h"
#include <iostream>

using namespace std;

int main() 
{ 
  string name; 
  cout << "Input your name please?" << endl; 
  cin >> name; 

  if
      {
          (name == "Bart Simpson")  
    cout << "You have been very naughty" << endl; 
  }
return 0;
}

I cant find the error in this piece of code could anyone please insight me? I ran the debugging but the errors are un-understandable..

#include "stdafx.h"
#include <iostream>

using namespace std;

int main() 
{ 
  string name; 
  cout << "Input your name please?" << endl; 
  cin >> name; 

  if
      {
          (name == "Bart Simpson")  
    cout << "You have been very naughty" << endl; 
  }
return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

£噩梦荏苒 2024-12-21 12:41:04

问题:

  1. 您缺少一些#include,这可能导致您的初始编译器错误。
  2. 您的 if 语句存在简单的语法错误。
  3. 使用流提取运算符永远不会产生内部带有空格的字符串。

以下内容应按您的预期工作:(

#include "stdafx.h"
#include <iostream>
#include <ostream>
#include <string>

using namespace std;

int main()
{
    cout << "Input your name please?" << endl;

    string name;
    getline(cin, name);
    if (name == "Bart Simpson")
    {
        cout << "You have been very naughty" << endl;
    }

    return 0;
}

您需要包含 std::stringstd::getlinestring 以及 ostreamstd::endl。)

Problems:

  1. You have some missing #includes, which probably caused your initial compiler errors.
  2. You have a simple syntax error with your if statement.
  3. Using the stream extraction operator will never yield a string with whitespace inside of it.

The following should work as you expect:

#include "stdafx.h"
#include <iostream>
#include <ostream>
#include <string>

using namespace std;

int main()
{
    cout << "Input your name please?" << endl;

    string name;
    getline(cin, name);
    if (name == "Bart Simpson")
    {
        cout << "You have been very naughty" << endl;
    }

    return 0;
}

(You need to include string for std::string and std::getline, and ostream for std::endl.)

云胡 2024-12-21 12:41:04

我认为括号放在错误的位置只是粘贴代码时的问题

if(名称==“巴特·辛普森”)

name 永远不会等于 "Bart Simpson",因为提取字符串在遇到空格时会停止;所以它只会是“Bart”。也许您想使用 getline() 来代替?

I assume the bracket in the wrong place is just a problem when pasting the code

if(name == "Bart Simpson")

name will never equal "Bart Simpson", since extracting a string stops when it encounters whitespace; so it would only be "Bart". Perhaps you want to use getline() instead?

℡寂寞咖啡 2024-12-21 12:41:04

应该是

if (name == "Bart Simpson")
{
    cout << "You have been very naughty" << endl;
}

并且您需要包含

Should be

if (name == "Bart Simpson")
{
    cout << "You have been very naughty" << endl;
}

And you need to include <string>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文