是否可以将一行打印的语句存储为字符串,然后在其他部分输出该行?
如果没有那么还有其他方法吗?如果用户未输入打印的行,但需要使用它来显示其他部分。
尝试谷歌,但仍然没有任何线索。
我使用的是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;
}
答案 0 :(得分:1)
你有三个问题,第一个问题是line[X]
是一个单个字符,你尝试给它分配一个字符串(line[20]
是不合适的)。第二个问题是您无法分配数组,您可以根据定义初始化数组,或者您可以使用例如复制。 strcpy
。第三个错误是您尝试复制到数组的字符串多超过20个字符。
答案 1 :(得分:0)
line[20]
。"You had selected first choice"
,这是29个字符和30个字节(包括终止空字符)。scanf("%s", &line);
是未定义的行为:"%s"
期望char*
而&line
是char(*)[20]
。您可以使用strcpy()
复制以null结尾的字符串。
固定代码:
#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;
}
答案 2 :(得分: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);