Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::getline error

Tags:

c++

getline

I'm new to C++, could someone please explain to me why I received the below errors when I do use "std::getline"? Here's the code:

#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

However, the program would run and compile when I used "getline" with "using namespace std;" instead of 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;
} 

Thank you!

like image 864
user2925557 Avatar asked Dec 11 '22 09:12

user2925557


2 Answers

The errors are not from std::getline. The error is you need to use std::string unless you use the using namespace std. Also would need std::endl.

like image 174
woolstar Avatar answered Dec 13 '22 21:12

woolstar


You need to use std:: on all the identifiers from that namespace. In this case, std::string and std::endl. You can get away without it on getline(), since Koenig lookup takes care of that for you.

like image 25
Fred Larson Avatar answered Dec 13 '22 22:12

Fred Larson