变量和scanf函数的问题
问题描述:
我对c编程语言很陌生。我写了这段代码,我想知道是否有任何方法 写这个代码更短,更有效?变量和scanf函数的问题
代码:
#include <stdio.h>
int main(){
printf("This is my first program.\nPlease put in your name...\n");
char letter[5];
scanf("%c%c%c%c%c%c", &letter[0], &letter[1], &letter[2], &letter[3], &letter[4], &letter[5]);
if(letter[0] == 't' && letter[1] == 'r' && letter[2] == 'a' && letter[3] == 'v' && letter[4] == 'i' && letter[5] == 's'){
printf("Access Granted\nWelcome Travis.\n");
return 0;
}
else{
printf("You are not autorized.\nThis program will exit now...\n");
getchar();
}
}if(letter[0] == 'b' && letter[1] == 'o' && letter[2] == 'b'){
printf("Access Granted\nWelcome Bob.\n");
return 0;
}
答
scanf("%c%c%c%c%c%c", &letter[0], &letter[1], &letter[2], &letter[3], &letter[4], &letter[5]);
是错误的,因为letter
是5元长,指标0-4。所以,在上面的scanf
中,letter[5]
不是有效的位置。你要走出阵列的界限。为了修正它,只要申报尺寸7的该阵列(6个字符为“特拉维斯” 1为\0
在末端)代替5:
char letter[7];
然后,scanf
可以缩短使用%s
:
scanf("%6s",letter);
接下来,
if(letter[0] == 't' && letter[1] == 'r' && letter[2] == 'a' && letter[3] == 'v' && letter[4] == 'i' && letter[5] == 's')
而且
if(letter[0] == 'b' && letter[1] == 'o' && letter[2] == 'b')
可以利用从string.h
头strcmp
功能缩短,使用逻辑或运算合并:
if(strcmp(letter,"bob")== 0 || strcmp(letter,"travis") == 0)
{...}
全部放在一起,
#include <stdio.h>
#include <string.h>
int main(){
printf("This is my first program.\nPlease put in your name...\n");
char letter[7];
scanf("%6s", letter);
if(strcmp(letter,"bob")== 0 || strcmp(letter,"travis") == 0)
printf("Access Granted\nWelcome %s.\n",letter);
else
printf("You are not autorized.\nThis program will exit now...\n");
getchar();
return 0; //you don't need these in every if and else.
}
+0
很快回复!我真的很喜欢这个论坛:) – travisjayday 2014-11-01 16:15:55
答
在这里你去
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int len_max = 128;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
current_size = len_max;
printf("\nEnter your string value:\n");
if(pStr != NULL)
{
int c = EOF;
unsigned int i =0;
//accept user input until hit enter or end of file
while ((c = getchar()) != '\n' && c != EOF)
{
pStr[i++]=(char)c;
//if i reached maximize size then realloc size
if(i == current_size)
{
current_size = i+len_max;
pStr = realloc(pStr, current_size);
}
}
pStr[i] = '\0';
printf("\nLong String value:%s \n\n",pStr);
//compare pStr with your defined string for authentication.
//e.g if(pStr=="myString"){printf("Access granted!");}
//free memory
free(pStr);
pStr = NULL;
}
return 0;
}
对于工作代码和代码审查 - 请参阅codereview.stackexchange.com – 2014-11-01 14:50:06
修复后一对大括号:http://coliru.stacked-crooked.com/a/ac471e129d93ece1 – chris 2014-11-01 14:50:06
你读过[scanf(3)]的文档吗(http://man7.org/linux/man-pages/man3/ scanf.3.html)(你应该测试它的结果)?你是否编译过所有警告和调试信息('gcc -Wall -Wextra -g')?你**使用调试器**('gdb')吗? – 2014-11-01 15:49:04