相当于c ++中的Console.ReadLine()

时间:2012-10-09 18:46:52

标签: c++ string scanf readline

screenshot 我的老师刚刚用c ++给了我一个作业,我试图用scanf得到一个字符串,但它只能输入最后输入的字符。有人可以帮我吗?我在c ++中寻找相当于console.readline()的东西。

编辑:我还必须能够通过指针存储值。

所以图片显示当前在后台运行的代码,它应该停止在No assurance maladie:并等待输入但跳过它。

getline(cin,ptrav-> nam);有效,但由于某种原因它跳过一条线......

2 个答案:

答案 0 :(得分:29)

您正在寻找std::getline()。例如:

#include <string>
std::string str;
std::getline(std::cin, str);

当你说我必须能够通过指针存储值时,我不知道你的意思。

更新:查看更新后的问题,我可以想象发生了什么。读取选择的代码,即数字1,2等不是读取换行符。然后你调用消耗换行符的getline。然后再次调用getline来获取字符串。

答案 1 :(得分:7)

根据MSDN, Console::ReadLine

Reads the next line of characters from the standard input stream.

C ++ - Variant(不涉及指针):

#include <iostream>
#include <string>

 int main()
{
 std::cout << "Enter string:" << flush;
 std::string s;
 std::getline(std::cin, s);
 std::cout << "the string was: " << s << std::endl;
}

<小时/> C-Variant(带缓冲区和指针)也是 适用于C ++编译器,但不应使用:

 #include <stdio.h>
 #define BUFLEN 256

 int main()
{
 char buffer[BUFLEN];   /* the string is stored through pointer to this buffer */
 printf("Enter string:");
 fflush(stdout);
 fgets(buffer, BUFLEN, stdin); /* buffer is sent as a pointer to fgets */
 printf( "the string was: %s", buffer);
}

<小时/> 根据你的代码示例,如果你有一个结构patient(在David hefferman的评论之后纠正):

struct patient {
   std::string nam, nom, prenom, adresse;
};

然后,以下内容应该有效(通过逻辑思考,在solved by DavidHeffernan附加问题后添加ios::ignore。请不要在代码全部中使用scanf

...
std::cin.ignore(256); // clear the input buffer

patient *ptrav = new patient;

std::cout << "No assurance maladie : " << std::flush;
std::getline(std::cin, ptrav->nam);
std::cout << "Nom : " << std::flush;
std::getline(std::cin, ptrav->nom);
std::cout << "Prenom : " << std::flush;
std::getline(std::cin, ptrav->prenom);
std::cout << "Adresse : " << std::flush;
std::getline(std::cin, ptrav->adresse);
...
相关问题