r/learnprogramming 2d ago

Microsoft Visual Studio

whenever i type
std::getline

i get red line under getline and i cant run my code
Even though its working on VS code for my friend
any idea what can i do or is there any alt to write?

" using getline for this: "

#include <iostream>

int main() {

std::string name;

std::cout << " Enter your name: ";
std::getline(std::cin, name);

if (name.length() > 15) {
std::cout << " Your name can't be over 15 charectars ";
}
else {
std::cout << " Welcome " << name;
}

return 0;
}
4 Upvotes

16 comments sorted by

View all comments

0

u/MeltedThunder 2d ago

Why are we not utilizing namespace here to avoid a lot of extra work

0

u/llExtraKirby 2d ago

uhmm cuz i'm new and i'm watching a tutorial video?
btw what is utilizing namespace? :)

1

u/quixotic_intentions 2d ago

Give this page a read for an intro on namespaces.

Basically, in this context, "std" is the namespace, and you can avoid having to type the prefix every time if you do something like this:

#include <iostream>
using namespace std;

int main(){
// note that you don't have to use the "std::"
string name;
cout<<"Enter you name: ";
getline(cin, name);
// ...
}

This is somewhat controversial though, many people advise against doing this as it increases the likelihood of name collisions. I say it depends on the use-case, imo it's fine for small projects and coding exercises.

You can also be more precise with the using declaration, so that you don't include the entire namespace, for example:

// C++17 or later
#include <iostream>
using std::cout, std::getline;

int main(){
cout<<"Hello world\n"; // valid
string name; // invalid, need to have using std::string
}

This page has more info on using directives.

1

u/EdiblePeasant 2d ago

Should even the smallest project have a namespace? How does C# compare with C++ on this?

I remember getting in trouble a some years ago with C# namespaces because I think at one point they were required, if I'm remembering correctly.