如何从数组中取出字符并将它们存储在变量中?

时间:2016-05-12 06:21:07

标签: c arrays

#include <stdio.h>
#include <stdlib.h>

int main()
{

    int agecalc;
    int nextyr;
    int birthday;
    int currentday;
    int agecalcu;
    int randomnumbers;

    birthday = 1987;
    currentday = 2016;
    nextyr = currentday + 1;
    agecalc = currentday - birthday;
    randomnumbers = 7890;

    char My[] = "Sayan Banerjee";

    printf("%s 's birthday is %.3d \n", My , agecalc);

    agecalcu = agecalc + 1;

/* alternatively I can use one int and change the variable stored in agecalc by stating that
agecalc = currentday - birthday +1; But I think that is just messy and disturbs a lot of code. declaring a new int is
better and less intrusive. this way when I may need to use agecalc again, i dont have to worry about the value stored in that
variable. */

    printf("%.5s will turn %.3d on %d.\n \a", My , agecalcu , nextyr);

    printf("The username for %s is %.6d \n", My , randomnumbers);
    // the thing here is that I cannot shorten a value stored in a value unless its in an array
    // but I can express it in other ways like 1 to 01.
    /* The thing is that I cannot store two %s in one argument/code. this freezes the code. better way would be to
    create another variable and then try to edit that.*/

    //this is an experiment to see whether I can take characters from an array and store it in a variable
    int user;


    My [0,1,2,3,4,5] = user;

    printf("%s is also %s", My , user );


   return 0;
}

我的主要问题是在最后一行。我是编码的新手,刚刚开始学习。我只是在玩耍,注意到如果我在同一个参数中输入两个%s,程序会崩溃。所以,我在考虑是否可以在数组中使用某些字符并将它们存储在变量中然后打印出来?

有可能吗?或者我只是以错误的方式看待这个? 对不起凌乱的帖子。 谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

My [0,1,2,3,4,5] = user;

这一行相当于说

My[5] = user;

这是因为comma运算符

//this is an experiment to see whether I can take characters from an array and store it in a variable

你可以。但是你现在正在做的是为5th数组的My元素分配一个未赋值的值。 int val = My[5]完全可以,但不是相反。

崩溃正在发生,因为您的代码试图将整数解释为null terminated string,因为您提供了%s格式说明符

printf("%s is also %d", My , user ); // %d for integers

您当前状态的代码位于Undefined Behavior土地。

要将现有数组中的某些字符复制到目标数组中,您需要多个变量。单个变量只包含一个字符。

char user[6];
user[5] = '\0'; // fill the last character as null to be a valid C string
user[0] = My[0];
user[1] = My[1];
user[<any other index you want>] = My[<The index you want>];

您可以通过简单地使用string.h中的函数来节省更多精力,时间和精力,strncpy具有一系列用于字符串操作的实用程序。您当前的问题可能需要{{3}}

作为正交建议,使用编译器支持的最高警告级别编译代码。编译器会在编译时喊出这些问题。

例如gcc -Wall filename.c

答案 1 :(得分:0)

以下行不符合您的想法:

这样:

My [0,1,2,3,4,5] = user;

实际上与此相同:

My [5] = user;

了解comma operator

无论如何,您无法将整个My数组存储在单个int变量中。

您正在使用%s打印user,这不是char*,而是int

printf("%s is also %s", My , user );

这会导致未定义的行为,很可能是现代系统崩溃。

关于你的问题,有点不清楚,你可能想要这个:

#include <string.h>
...
char user[20];
strcpy(user, My);

printf("%s is also %s", My , user);

将打印:

Sayan Banerjee is also Sayan Banerjee