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!
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With