Reputation: 33
string name,date,dateOfBirth,address,phoneNumber;
int age;
int citizenshipNumber,accountNumber,choiceForMenu;
float amount;
void createAccount(){
system("cls");
cout<< setw(40);
cout<< "ADD RECORD"<<endl;
cout<<endl;
printf("Enter today's date(mm/dd/yyyy):");
scanf("%s" , &date);
printf("Enter the name:");
scanf("%s", &name);
printf("Enter the date of birth(mm/dd/yyyy):");
scanf("%s" , &dateOfBirth);
printf("Enter the age:");
scanf("%d",&age);
printf("Enter the address:");
scanf("%s", &address);
printf("Enter the citizenship number:");
scanf("%d", &citizenshipNumber);
printf("Enter the phone number:");
scanf("%s", &phoneNumber);
printf("Enter the amount of deposit:");
scanf("%f", &amount);
system("pause");
}
After I input the address, the citizenship number, phone number, and amount deposited ends up being on the same line and not allowing me to input anything, so can anyone help me fix that problem. Thank you!
Upvotes: 1
Views: 104
Reputation: 126203
Your code has undefined behavior, as you can't use scanf to read into std::string, but the problem you are reporting is probably independent of that.
When you read a "string" (with either scanf("%s",
... or cin >> var
where var
is a std::string
), you are reading a whitespace-delimited token, NOT a line. The call will stop reading as soon as it sees a space or tab (or anything else defined as whitespace in the current locale) after reading at least one non-whitespace character. So if you enter a line with spaces in it (eg, your address contains at least one space), it will stop at that space and leave the rest of the line to be read by future scanf
or cin >>
calls. As a result, you'll see all your following prompts pile up on a single line as the code reads the rest of the address line as whatever it is that you are reading, rather than waiting for more input lines.
If you want to read lines of input (rather than whitespace delimited text), you should use fgets (C) or getline (POSIX C or C++)
Upvotes: 1
Reputation: 3495
You can' t use scanf with std::string parameter in this way. If you want you can try :
std::string str(50, ' ');
if ( scanf("%*s", &str[0], str.size()) == 1) {
// ...
}
If you are compiling with c++17 you can try to use data().
But in general these are not the best solutions. In general scanf does not accept any class of C++.
I suggest you to use the C++ methods when use C++, so that you can avoid this error. For example std::cin could be a solution.
Upvotes: 1