c++ - scanf不接受输入

标签 c++ printf scanf

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");
}

输入地址后,公民编号,电话号码和存款金额最终显示在同一行上,并且不允许我输入任何内容,因此任何人都可以帮助我解决该问题。谢谢!

最佳答案

您不能以这种方式将scanf与std::string参数一起使用。
如果您愿意,可以尝试:

std::string str(50, ' ');
if ( scanf("%*s", &str[0], str.size()) == 1) {
    // ...
}

如果使用c++ 17进行编译,则可以尝试使用data()。

但是总的来说,这些并不是最佳的解决方案。通常scanf不接受任何C++类。

我建议您在使用C++时使用C++方法,这样可以避免此错误。
例如std::cin可能是一个解决方案。

关于c++ - scanf不接受输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59603303/

相关文章:

c++ - 带有 'not declared' 的“ undefined reference ”

c++ - 初始化对象时丢弃placement new返回值是否可以

c - 为什么使用 asprintf() 而不是 sprintf()?

c++ - printf 的整数参数的零填充宽度和精度是否相同?

自定义结构返回函数停留在输入上?

c++ - 为什么变长数组不是 C++ 标准的一部分?

c++ - 函数中的 const 数组与静态 const 数组

c - 调用 printf() 会产生什么值?

C 基于用户输入的二维数组

c - 在 c 中为 'fscanf' 使用定界符