我有一个代码片段,我正在用它来学习一些C语言。
char* input( char *s ){
scanf("%[^\n]%*c",s);
return s;
}
void main()
{
printf("Welcome to a string input/output example written in C! \n");
printf("Type e to exit \n");
printf(" \n");
while (0 == 0){
printf("> ");
char str[100];
input( str );
//All off this code works perfectly until the switch statement, which apparently cannot recognized the 'e' case:
switch(str){
case 'e' : break;
default : printf("Your string is: %s \n", str);
}
}
}
然而,当这段代码运行时,它返回的字符串很好,然而在switch语句中,它默认为默认,即使 "str "的值是 "e",它也会返回。
你的字符串是: e
而不是退出。 请帮助这是非常奇怪的...
你不能在C语言中对一个字符串使用开关。你现在做的是在开关中使用数组str中第一个字符的指针。这就是为什么总是去默认部分。一个好的方法是使用strcmp:int strcmp(const char *str1, const char *str2);如果返回值<0,则表示str1小于str2。
如果返回值> 0则表示str2小于str1。
如果返回值=0,则表示str1等于str2。
char str2[]="e";
if(strcmp(str, str2))
printf("Your string is: %s \n", str);
else
break;
另外不要使用while(0==0),要使用while(1)。
你可以不切换字符串。你可以使用 if ... else if
而不是。
while (1){
printf("> ");
char str[100];
input( str );
if(strcmp(str, "e") == 0){ // type e to exit
break;
} else if (strcmp(str, "abc") == 0) { // if you type abc
// do something
} else if (strcmp(str, "def") == 0) { // if you type def
// do something
} else { // it's a mimic of default in switch statement.
printf("Your string is: %s \n", str);
}
}
使用 strcmp
来比较字符串。在你的代码中 'e'
是字符,而不是字符串,你必须使用 "
而不是 '
点击这里查看更多信息 C语言中换弦的最佳方法
如果你还想要一个 switch
,改为: 如何对字符串进行switch和case?
在switch中的break语句会退出 开关 语句。如果switch在一个循环里面,它不会退出循环。只是switch语句。
太糟糕了,你的编译器没有警告你试图在字符串指针上切换而不是在第一个 性格 的字符串数组。 我的说:"错误C2050:
"错误C2050: 开关表达式不完整"
你仍然可以用:
switch(str[0])
(如果你在终端空值上添加一个额外的检查,以确定它是一个1字符的字符串)
老实说,我不认识你的scanf()语法,但我从来不用scanf(),因为如果你不小心的话,它可能会意外地超载你的缓冲区。 相反,我会使用getchar()来一次读取一个字符,并有最大限制。
最后,你的switch break只会脱离内部的switch语句。 你需要第二个break来脱离包围循环。
确保我没有犯错,或者进一步修改。
#include <stdio.h>
#include <ctype.h>
char* input( char *s, size_t max ){
size_t i = 0;
int c;
int skipped_space = 0;
for(;;) {
c = getchar();
if(EOF == c) {
// error
break;
}
if(!skipped_space) {
if(!isspace(c)) {
skipped_space = 1;
if(i < max) {
s[i++] = c;
}
}
} else {
if(isspace(c)) {
break;
}
if(i < max) {
s[i++] = c;
}
}
}
if(EOF != c && i < max) {
// success
s[i] = '\0';
} else {
// failure or buffer overrun
s = NULL;
}
return s;
}
void main()
{
int done = 0;
printf("Welcome to a string input/output example written in C! \n");
printf("Type e to exit \n");
printf(" \n");
for(;;) {
printf("> ");
char str[100];
if(input( str, 100 )) {
switch(str[0]){
case 'e' :
if('\0' == str[1]) {
done = 1;
break;
}
default:
printf("Your string is: \"%s\" \n", str);
break;
}
if(done)
break;
} else {
printf("Error.\n", str);
}
}
}