ToString()出错

时间:2014-12-13 17:52:28

标签: c tostring

我是c的新手。请帮帮我

为什么我使用eclipse

会收到此错误
Multiple markers at this line
- request for member 'ToString' in something not a structure or union
- Method 'ToString' could not be resolved

这是我的代码

#include <stdio.h>

int main()
{
    int s = 5;
    int n = 4;
    char g = s.ToString();
    char l = n.ToString();
    printf(g+l);

    return 0;
}

enter image description here

2 个答案:

答案 0 :(得分:1)

sn只是int s;他们没有ToString()方法。另外,正如@remyabel指出的那样,char不是用于存储字符串值的合适类型,无论如何;它只存储一个字符。

您根本不需要将int转换为字符串来完成您正在尝试完成的任务,因此您实际上需要这样的内容:

#include <stdio.h>
int main()
{
    int s = 5;
    int n = 4;

    printf("%d%d", s, n); // you can't add l to g here!

    return 0;
}
// output 54

DEMO

哦,使用更多描述性变量名称!

编辑:要按照评论中的要求保存字符串,您可以这样做:

char myString[10];
sprintf(myString, "%d%d", s, n); // myString is now "54"

答案 1 :(得分:0)

我建议从头开始学习C语言教程。使用ToString并不是唯一错误的。你可以用这种方式重写它,它应该工作(假设你想打印“54”):

#include <stdio.h>

int main()
{
    int s = 5;
    int n = 4;
    char g = '0' + s;
    char l = '0' + n;
    printf("%c%c", g, l);

    return 0;
}

但这仅在sn小于10时才有效,而且由于printf用于格式化和打印不同类型的值,因此过于复杂。这也可行:

#include <stdio.h>

int main()
{
    int s = 5;
    int n = 4;
    printf("%d%d", s, n);

    return 0;
}

如果您想将字符串用于除打印之外的其他内容,答案取决于您想要做什么。

相关问题