简体   繁体   English

将一行存储为字符串,然后在C代码中输出

[英]Store a line as string and Output later in C code

Is it possible to store a line of printed statement as string and output the line later in other part ? 是否可以将打印语句的一行存储为字符串,然后在另一部分稍后输出?

If no then is there other method ? 如果否,还有其他方法吗? Provided that the line printed is not entered by user but need to use it to display at other part. 如果打印的行不是由用户输入的,而是需要使用它来显示在其他部分。

Tried google but still no clue about it. 尝试过谷歌,但仍然没有任何线索。

I'm using Visual Studio 2010 and what I had tried so far is : 我正在使用Visual Studio 2010,到目前为止我尝试过的是:

#include<stdio.h>
int main()
{
int choice;
char line[20];    //variable to store the line 
printf("Enter your choice\n");
scanf("%d", &choice);
switch(choice){
case 1:
    printf("You had selected first choice\n");    //this line wanted to be store as string and output at bottom 
line[20]="You had selected first choice"; // error C2440
scanf("%s", &line); // probably I could use this to store the line ? 
break;

default:
    exit(0);
}
printf("%s", line); // display the line which has been store in above 
return 0;
}

You have three problems, the first is that line[X] is a single character and you try to assign a string to it ( line[20] is out of bounds by the way). 您遇到三个问题,第一个问题是line[X]单个字符,然后您尝试为其分配一个字符串(顺便说一句, line[20]超出范围)。 The second problem is that you can't assign to an array, you can initialize an array at definition, or you can copy to it, using eg strcpy . 第二个问题是您不能分配给数组,不能在定义时初始化数组,也可以使用strcpy将其复制到数组。 The third error is that the string you try to copy to the array is much longer than 20 characters. 第三个错误是,试图复制到阵列的字符串超过20个字符长很多

  • Do not access line[20] , which is out-of-range. 不要访问超出范围的line[20]
  • 20-byte array is too small to store "You had selected first choice" , which is 29-character and 30-byte (incluting terminating null character) long. 20字节的数组太小,无法存储"You had selected first choice" ,它的长度为29个字符,为30个字节(包括终止空字符)。
  • scanf("%s", &line); is undefined behavior because of type mismatch: "%s" expect char* and &line is char(*)[20] . 由于类型不匹配而导致未定义行为: "%s"期望为char*&linechar(*)[20]

You can use strcpy() to copy null-terminated strings. 您可以使用strcpy()复制以空值结尾的字符串。

Fixed code: 固定代码:

#include<stdio.h>
#include<stdlib.h> // for using exit()
#include<string.h> // for using strcpy()
int main(void)
{
    int choice;
    char line[64];    //variable to store the line 
    printf("Enter your choice\n");
    scanf("%d", &choice);
    switch(choice){
    case 1:
        printf("%s\n", strcpy(line, "You had selected first choice"));
        break;

    default:
        exit(0);
    }
    printf("%s", line); // display the line which has been store in above 
    return 0;
}
// In general do a formatted output to char array,  
// and use it as you like.  
sprintf(line, "%s", "You had selected first choice\n");  
printf("%s", line);  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM