简体   繁体   English

在 C++ 中获取用户输入的字符串

[英]Getting a string input from user in C++

This is the piece of code I am getting error in. Yes I have `using namespace std这是我遇到错误的一段代码。是的,我有`using namespace std


string age2;

cin.ignore();

getline(cin, age2);

cout << "Your age is " << age2;

This is giving me error -> "getline is not defined"这给我错误 - >“getline is not defined”

I tried searching up and tried all the solutions but none of them worked.我尝试搜索并尝试了所有解决方案,但没有一个有效。

This code here works fine:这段代码在这里工作正常:

#include <iostream>
#include <string>

int main(){

std::string age;

std::cin.ignore();

std::getline(std::cin, age);

std::cout << "Your age is " << age;

return 0;
}

so there must be something your missing in your example所以你的例子中一定有你遗漏的东西

also if your doing age, you should use an int instead of a string, like this:另外,如果您年龄较大,则应该使用 int 而不是字符串,如下所示:

#include <iostream>
#include <string>

int main(){

int age;

std::cin.ignore();

std::cin >> age;

std::cout << "Your age is " << age;

return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM