C ++ std :: getline错误

问题描述 投票:2回答:4

我是C ++的新手,有人可以向我解释为什么当我使用“ std :: getline”时为什么收到以下错误?这是代码:

#include <iostream>
#include <string>

int main() {

  string name;  //receive an error here

  std::cout << "Enter your entire name (first and last)." << endl;
  std::getline(std::cin, name);

  std::cout << "Your full name is " << name << endl;

  return 0;
}


ERRORS:
te.cc: In function `int main()':
te.cc:7: error: `string' was not declared in this scope
te.cc:7: error: expected `;' before "name"
te.cc:11: error: `endl' was not declared in this scope
te.cc:12: error: `name' was not declared in this scope

但是,当我将“ getline”和“ using namespace std”一起使用时,程序将运行并编译;而不是std :: getline。

#include <iostream>
#include <string>

using namespace std;

int main() {

  string name;

  cout << "Enter your entire name (first and last)." << endl;
  getline(cin, name);

  cout << "Your full name is " << name << endl;
  return 0;
} 

谢谢!

c++ getline
4个回答
8
投票

错误不是来自std::getline。错误是您需要使用std::string,除非您使用using namespace std。还需要std::endl


4
投票

您需要对该名称空间中的所有标识符使用std::。在这种情况下,为std::stringstd::endl。您可以在getline()上不加使用它,因为Koenig查找将为您解决这个问题。


1
投票
#include <iostream>
#include <string>

int main() 
{
    std::string name;  // note the std::

    std::cout << "Enter your entire name (first and last)." << std::endl; // same here
    std::getline(std::cin, name);

    std::cout << "Your full name is " << name << std::endl; // and again

    return 0;
}

您只需要声明std名称空间中各种元素的名称空间(或者,您可以删除所有std::,并在包含之后放置using namespace std;行。]


0
投票

尝试一下:

 #include <iostream>
#include <string>

int main() 
{
     std::string name; 

      std::cout << "Enter your entire name (first and last)." << 
      std::endl;

      while(getline(std::cin, name))
      {
            std::cout <<"Your name is:"<< name << '\n';

     }

  return 0;
}

请喜欢。

© www.soinside.com 2019 - 2024. All rights reserved.