equivalent of Console.ReadLine() in c++
According to MSDN, Console::ReadLine:
Reads the next line of characters from the standard input stream.
The C++-Variant (no pointers involved):
#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;
}
The C-Variant (with buffers and pointers), also works in with C++ compilers but should not be used:
#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);
}
According to your code example, if you have a struct
patient
(corrected after David hefferman's remark):
struct patient {
std::string nam, nom, prenom, adresse;
};
Then, the following should work (added ios::ignore
after additional problem has been solved by DavidHeffernan by logical thinking). Please DO NOT use scanf
in your code AT ALL.
...
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);
...
You are looking for std::getline()
. For example:
#include <string>
std::string str;
std::getline(std::cin, str);
I've little idea what you mean when you say I must also be able to store the value through a pointer.
Update: Looking at your updated question, I can imagine what is happening. The code that reads the choice, i.e. the number 1, 2, etc. is not reading the newline. Then you call getline
which consumes the newline. And then you call getline
again which fetches the string.