扫描仪不接受输入

问题描述 投票:1回答:2
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");
}

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

c++ printf scanf
2个回答
1
投票

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

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

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

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

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


1
投票

您的代码具有未定义的行为,因为您不能使用scanf来读取std :: string,但是您要报告的问题可能与此无关。

[当您读取“字符串”(使用scanf("%s", ...或cin >> var,其中varstd::string时),您正在读取由空格分隔的标记,而不是一行。在读取至少一个非空白字符后,该调用将在看到一个空格或制表符(或在当前语言环境中定义为空白的任何其他内容)后立即停止读取。因此,如果您输入的行中有空格(例如,您的地址至少包含一个空格),它将停在该空格处,并保留该行的其余部分以供将来的scanfcin >>调用读取。结果,您将看到以下所有提示都堆积在一行上,因为代码将按照您正在读取的内容读取地址行的其余部分,而不是等待更多的输入行。

如果要读取输入的(而不是用空格分隔的文本),则应使用fgets(C)或getline(POSIX C或C ++)]

© www.soinside.com 2019 - 2024. All rights reserved.