C++中与Console.ReadLine()等效的函数是什么?

18

屏幕截图 我的老师给了我一个C++作业,我正在尝试使用scanf获取一个字符串,但它只能获取输入的最后几个字符。有人可以帮助我吗?我正在寻找在C++中与console.readline()等价的方法。

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

所以图片显示了当前正在后台运行的代码,它应该停在“没有保险医疗:”处等待输入,但跳过了它。

getline(cin, ptrav->nam);可以工作,但出于某种原因会跳过一行...


2
在C/C++中使用fgets,在C++中使用std::getline - rubber boots
2
请勿使用代码截图,而是制作一个仅包含相关代码的示例,并描述您的输入以及期望和实际输出。基本上,在发布问题之前,请对问题进行一些隔离/诊断工作,而不仅仅是“我有这个问题,它无法正常工作”。 - millimoose
3个回答

37

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

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

当你说“我还必须能够通过指针存储该值”时,我有点不明白你的意思。

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


是的,我相信scanf()将单词读取为字符串。fgets(...,stdin)也可能有效。 - user645280
1
这些是处理C字符串的C函数。我们需要的是C++字符串。 - David Heffernan
1
好的,你可以这样做:getline(cin, ptrav->nam)。这是因为字符串参数通过引用传递给getline函数。 - David Heffernan
2
截图无法运行您的代码。请创建最小可能的程序来说明您的问题并发布它。我认为这将是一个新的问题。我认为您在这里提出的问题已经得到了回答。 - David Heffernan
#include "string" must be added or else you might get identifier "getline" is undefined - Junior Mayhé
显示剩余6条评论

7

根据MSDN,Console::ReadLine

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

C++-变量(不涉及指针):
#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;
};

接下来,以下内容应该有效(在解决了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);
...

0

新的C++支持cin和cout关键字。你可以使用它们。

Ex


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接