【问题标题】:strings and ints in functions函数中的字符串和整数
【发布时间】:2019-04-24 01:06:04
【问题描述】:

我是 C++ 的新手,目前正在学习函数。我很难让这段代码正常工作。我将 C++ 与 <cstdio> 库一起使用,因为我的老师希望我使用 C++。漏洞是使用<cstdio> 所以代码是:

#include <iostream>
#include <cstdio>

void letters(char name[], char discipline[])
{
    printf("type a name:\n\n");
    scanf("%s", &name);

    printf("\n\ntype a discipline:\n\n");
    scanf("%s", &discipline);

    printf("\n\nname: %s\n\ndiscipline: %s", name, discipline);
}

void calcsum(int point1, int point2, int sum)
{   
    printf("\n\ntype a point:\n\n");
    scanf("%i", &point1);

    printf("\n\ntype a second point:\n\n");
    scanf("%i", &point2);

    sum = point1 + point2;
    printf("\n\nsum is: %i", sum);
}

int main(int argc, char** argv)
{
    char name[100];
    char discipline[100];
    int point1, point2, sum;

    letters(name, discipline);
    calcsum(point1, point2,sum);    

    return 0;
}

在要求输入规则之前,一切正常。当我输入时,它要求输入名称,然后出现一个错误选项卡。这发生在我所有涉及 char 数组和任何其他数据类型的代码中。

【问题讨论】:

  • 好吧,你应该使用std::string而不是这些原始字符串,并且你已经包含了iostream,所以你也应该使用它,即将printfscanf替换为std::coutstd::cin 因为它是 c++ 而不是 c
  • 如果您应该使用 C++,那么您可能不应该尝试编写 C。
  • 老师们通常不喜欢“漏洞”的解决方案,所以如果你失败了也不要感到惊讶。

标签: c++ function


【解决方案1】:

漏洞是利用&lt;cstdio&gt;

我不确定你的老师是否会喜欢你的选择,但你没有要求。

printf("type a name:\n\n");
scanf("%s", &name);

printf("\n\ntype a discipline:\n\n");
scanf("%s", &discipline);

namediscipline 已经是指针,您不必在它们上使用地址运算符 &amp; 将它们传递给 scanf()

此外,没有理由将参数传递给您的函数calcsum()letters(),因为您不想传递任何数据。只需定义它们在函数中使用的变量:

void letters()
{
    printf("type a name:\n\n");
    char name[100];
    scanf("%99s", &name);  // read 99 characters + terminating '\0' max

    printf("\n\ntype a discipline:\n\n");
    char discipline[100];
    scanf("%99s", &discipline);  // NEVER use "%s" with scanf without specifying
                                 // a maximum width for field to read.

    printf("\n\nname: %s\n\ndiscipline: %s", name, discipline);
}

void calcsum()
{  
    printf("\n\ntype a point:\n\n");
    int point1;
    scanf("%i", &point1);

    printf("\n\ntype a second point:\n\n");
    int point2;
    scanf("%i", &point2);

    int sum = point1 + point2;    
    printf("\n\nsum is: %i", sum);

}

int main()  // there is also no need of taking parameters if you don't use them
{
    letters();  // no parameters needed since you don't
    calcsum();  // want to pass values to these functions

    // return 0;  main defaults to return 0 if there is no return-statement.
}

最后但并非最不重要的一点是,C++ 标准库的所有函数都驻留在命名空间std(或以下)中。这也适用于从 c 标准库继承的函数。所以

printf( /* ... */ );
scanf( /* ... */ );
// etc

应该是

std::printf( /* ... */ );
std::scanf( /* ... */ );

【讨论】:

  • 这里说要避免评论“谢谢”之类的东西,所以要坚持我说的好答案,该死的你应该是我的老师。
  • 所以我已经通过上面更正的代码学到了很多,但是当我在 DEVC++ 中运行它时,我得到了这个错误:'name,discipline,point1,point2' 没有在这个范围内声明。 redd 线在 main 函数、字母和 calcsum 中
猜你喜欢
  • 2016-04-30
  • 2014-01-26
  • 2017-02-05
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 2018-10-13
相关资源
最近更新 更多