【问题标题】:I have a bit of a problem, I can seem to understand this error我有点问题,我似乎可以理解这个错误
【发布时间】:2019-09-26 18:23:53
【问题描述】:

我正在创建一个程序,我需要在其中登录帐户并查看余额和到期日,但是在运行它时出现了一些错误。 这是我遇到的错误: [错误] 无法通过 '...' 传递非平凡可复制类型 'std::string {aka class std::basic_string}' 的对象

我尝试在线搜索如何修复,但仍然无法正常工作

这是我的代码:

#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
int main() {
    string names[2] = { "MARK", "EMILY" }, Ddate[2] = { "10/04/19","10/06/19" };
    int bal[2] = { 4500,6500 }, id_num[2] = { 1810784, 1810783 }, pword[2] = { 117611,594356 }, idnum, pw,i = 0;

    char check_bal,temp;
    printf("WELCOME TO STUDENT BILLING SYSTEM \n");
    printf("Would you like to check your balance? Y/N\n");
    scanf( "%c", &check_bal);
    temp = toupper(check_bal);
    check_bal = temp;

    if (check_bal == 'Y') {
        printf("ENTER YOUR ID NUMBER: ");
        scanf("%i", &idnum);
        printf("ENTER YOUR PASSWORD: ");
        scanf("%i", &pw);
        while (true) {
            if (idnum == id_num[i])
                break;
            else
                continue;
        }
        while (true) {
            if (pw == pword[i])
                break;
            else
                continue;
        }
        printf("HI %s, your balance is %i and the DUE DATE is: %s \n", names[i],bal[i],Ddate[i]);
}
else
    system("EXIT");

system("PAUSE");
return 0;

}

【问题讨论】:

  • 我建议你投资a couple of good books about C++,学习如何使用C++输入输出代替旧的C输入输出。
  • 所有使用%s 说明符的printf 操作都期望const char* 作为参数。你给他们std::string s。那是行不通的,并且是通过多个参数完成的。按照@Someprogrammerdude 的建议去做,并获得一本描述如何使用 C++ iostream 的好书。
  • 你的编译器应该告诉你是哪一行导致了错误。
  • @FrançoisAndrieux 考虑到system 创建了一个“shell”来运行命令,该命令仅退出该shell 而没有其他任何内容,该函数调用实际上是无用的。
  • @Someprogrammerdude 谢谢。

标签: c++ dev-c++


【解决方案1】:

代码在 g++ 中编译得很好,但输出垃圾。 使用 g++ -Wall 您会收到明智的警告:

warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘std::__cxx11::string’ {aka ‘std::__cxx11::basic_string<char>’} [-Wformat=]

这是 g++ 版本 8.3.0。

可以像这样挽救代码:

printf("HI %s, your balance is %i and the DUE DATE is: %s \n", names[i].c_str(),bal[i],Ddate[i].c_str());

但是请注意推荐使用 c++ 风格 io 的 cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多