Cout of a string is giving an error and a hard time some insight help pls?

爱⌒轻易说出口 提交于 2019-12-02 18:34:34

问题


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

回答1:


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.)




回答2:


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?




回答3:


Should be

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

And you need to include <string>



来源:https://stackoverflow.com/questions/8085892/cout-of-a-string-is-giving-an-error-and-a-hard-time-some-insight-help-pls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!