使用 strstr NULL 返回退出 for 循环
我在这里没有得到什么?
这工作得很好:
for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
found=strcmp( name, myContacts[i].cFirstName);
printf(" i %d\n", i);
}
printf(" \nName Found %s", myContacts[i-1].cFirstName );
但出于好奇,我也尝试使用 strstr()。
/*** This achieves the same functionality as above ***/
for ( i = 0; i < 5 ;i++ ){
found2=strstr( myContacts[i].cFirstName , name);
printf(" i %d\n", i);
if (found2 != NULL)
{
printf(" \nName Found %s", myContacts[i].cFirstName );
break;
}
}
然而,这不起作用:
for ( i = 0; i < 5 && found2 != '\0' ;i++ ){ //this does not work as above
for ( i = 0; i < 5 && found2 != NULL ;i++ ){ // this also is not wroking
found2=strstr( myContacts[i].cFirstName , name);
}
printf(" \nName Found %s", myContacts[i].cFirstName );
提前感谢您的建议。
完整代码:
# please take my codes with a grain of skepticism, I am still learning
# i know of sizeof(), but I rather not use it just for the purpose of my exercise
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXBUFFERSIZE 10
typedef struct contact {
char cFirstName[10];
char cLastName[10];
char cTelphone[12];
} address ; // end type
// function prototype
void printContacts( address * );
void printMenu();
char getChoice();
void storeContact( address [] , int *);
//int searchContact( address [] , char * );
void searchContact( address [] , char [] );
int main(){
char cSelection = 0;
address myContacts[5];
char buffer[MAXBUFFERSIZE];
int i ;
// initialize array to be zeros
for ( i = 0; i < 5 ; i++ ){
strcpy(myContacts[i].cFirstName, "0");
strcpy(myContacts[i].cLastName,"0");
strcpy(myContacts[i].cTelphone,"0");
}
strcpy(myContacts[0].cFirstName, "Jonny");
strcpy(myContacts[1].cFirstName, "Julia");
strcpy(myContacts[2].cFirstName, "Claudia");
strcpy(myContacts[3].cFirstName, "Aaron");
strcpy(myContacts[4].cFirstName, "Sebastian");
int iDel = -1 ; // store the position if one deleted
int iCount = 0 ; // counter for position in the array, when
// inserting names.
while ( cSelection != '5' ) {
printMenu();
cSelection = getChoice();
switch (cSelection) {
case '1':
printContacts( myContacts );
break;
case '2':
if ( ( iDel >= -1 ) && ( iCount < 5 ) ){
//printf("\niCount is %d ", iCount);
storeContact( myContacts, &iCount );
iCount++;
//printf("\nOutside storeContact, *Plocation %d", iCount );
}
if ( iCount >= 5 ) {
printf("\nThe Memory is full, consider deleting some"\
"Contacts");
}
break;
case '3':
{
printf("\nEnter a name or part of a name to search:\n");
fscanf(stdin, "%s", buffer);
getchar(); // clear the last enter
printf("\nThe line you entered was:\n");
printf("%s\n", buffer);
searchContact( myContacts, buffer );
break;
}
case '4':
//iDel=deleteContact( myContacts );
break;
}// end of switch
}// end of while
return 0;
} // end main
char getChoice(){
char cSelection = 'q'; //for the menu
/**** always scanf CHARS so you can check
* if digit or char !!! ****/
scanf("%s", &cSelection);
while ( strlen(&cSelection) != 1 ){
printf("\nChoich not understood, enter a number again:");
scanf("%s",&cSelection);
}
if ( isalpha(cSelection) ){
printf( "You entered a letter of the alphabet\n" );
cSelection = -1;
printf( "Illegal choice !!!" );
}
return cSelection;
}
void printContacts( address * myContacts ){
int i ;
for ( i = 0; strcmp(myContacts[i].cFirstName,"0") != 0 && i < 5 ; i++ ){
printf("\nmyContacts[%d].cFirstName: %s", i, \
myContacts[i].cFirstName );
}// end for
}
void printMenu(){
printf("\n\n\tSilly Phone Book\n\n");
printf("\n\n1\tPrint Phone Book\n");
printf("2\tAdd New Contact\n");
printf("3\tSearch For Contact\n");
printf("4\tDelete Contact\n");
printf("5\tQuit\n");
printf("\nSelect Action: ");
}
//void storeContact( address myContacts[] ){ //syntactic sugar
void storeContact( address * myContacts, int *Plocation ){
char ch; /* handles user input */
char buffer[MAXBUFFERSIZE]; /* sufficient to handle one line */
int x = 0;
x=*Plocation;
ch = getchar(); // clear the last enter
printf("Enter a name (<10 characters)\n");
//ch = getchar();
//char_count = 0;
//while( (ch != '\n') && (ch != EOF ) && (char_count < MAXBUFFERSIZE)) {
//buffer[char_count++] = ch;
//ch = getchar();
//}
//buffer[char_count] = 0x00; /* null terminate buffer */
//fgets(buffer,11,stdin);
fscanf(stdin, "%s", buffer); /* read from keyboard */
printf("\nThe line you entered was:\n");
printf("%s\n", buffer);
//TODO: add check that string is not too long!!!
// if we do that, the code won't blow here ?
strcpy(myContacts[x].cFirstName, buffer);
}
//int searchContact( address * myContacts, char name[] ){
void searchContact( address * myContacts, char * name ){
int found;
char *found2;
//printf("\nHey dude im buffer from inside searchContact: %s", name);
// iterate throught the array, print possible matches
int i = 0;
//for ( i = 0; i < 5 && found != 0 ;i++ ){
//for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
//found=strcmp( name, myContacts[i].cFirstName);
//printf(" i %d\n", i);
//}
//printf(" \nName Found %s", myContacts[i-1].cFirstName );
/*** This achieves the same functionality as above
for ( i = 0; i < 5 ;i++ ){
found2=strstr( myContacts[i].cFirstName , name);
printf(" i %d\n", i);
if (found2 != NULL)
{
printf(" \nName Found %s", myContacts[i].cFirstName );
break;
}
} ***/
for ( i = 0; i < 5 && &found2 != '\0' ;i++ ){ //this does not work as above
found2=strstr( myContacts[i].cFirstName , name);
printf("found %p i %d\n", found2, i);
//printf(" \nName Found %s", myContacts[i].cFirstName );
}
//return found;
} // end of searchContacts if ( isalpha(cSelection) ){
printf( "You entered a letter of the alphabet\n" );
cSelection = -1;
printf( "Illegal choice !!!" );
}
return cSelection;
}
void printContacts( address * myContacts ){
int i ;
for ( i = 0; strcmp(myContacts[i].cFirstName,"0") != 0 && i < 5 ; i++ ){
printf("\nmyContacts[%d].cFirstName: %s", i, \
myContacts[i].cFirstName );
}// end for
}
void printMenu(){
printf("\n\n\tSilly Phone Book\n\n");
printf("\n\n1\tPrint Phone Book\n");
printf("2\tAdd New Contact\n");
printf("3\tSearch For Contact\n");
printf("4\tDelete Contact\n");
printf("5\tQuit\n");
printf("\nSelect Action: ");
}
//void storeContact( address myContacts[] ){ //syntactic sugar
void storeContact( address * myContacts, int *Plocation ){
char ch; /* handles user input */
char buffer[MAXBUFFERSIZE]; /* sufficient to handle one line */
int x = 0;
x=*Plocation;
ch = getchar(); // clear the last enter
printf("Enter a name (<10 characters)\n");
//ch = getchar();
//char_count = 0;
//while( (ch != '\n') && (ch != EOF ) && (char_count < MAXBUFFERSIZE)) {
//buffer[char_count++] = ch;
//ch = getchar();
//}
//buffer[char_count] = 0x00; /* null terminate buffer */
//fgets(buffer,11,stdin);
fscanf(stdin, "%s", buffer); /* read from keyboard */
printf("\nThe line you entered was:\n");
printf("%s\n", buffer);
//TODO: add check that string is not too long!!!
// if we do that, the code won't blow here ?
strcpy(myContacts[x].cFirstName, buffer);
}
//int searchContact( address * myContacts, char name[] ){
void searchContact( address * myContacts, char * name ){
int found;
char *found2;
//printf("\nHey dude im buffer from inside searchContact: %s", name);
// iterate throught the array, print possible matches
int i = 0;
//for ( i = 0; i < 5 && found != 0 ;i++ ){
//for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
//found=strcmp( name, myContacts[i].cFirstName);
//printf(" i %d\n", i);
//}
//printf(" \nName Found %s", myContacts[i-1].cFirstName );
/*** This achieves the same functionality as above
for ( i = 0; i < 5 ;i++ ){
found2=strstr( myContacts[i].cFirstName , name);
printf(" i %d\n", i);
if (found2 != NULL)
{
printf(" \nName Found %s", myContacts[i].cFirstName );
break;
}
} ***/
for ( i = 0; i < 5 && found2 != '\0' ;i++ ){ //this does not work as above
found2=strstr( myContacts[i].cFirstName , name);
printf("found %p i %d\n", found2, i);
//printf(" \nName Found %s", myContacts[i].cFirstName );
}
//return found;
} // end of searchContacts
为了本次讨论的完整性,我添加了最终真正按照我想要的方式工作的内容。 这是在看完所有答案之后出现的,所以谢谢大家:
我忘记初始化指针:
char *found2=NULL;
现在以下循环按预期工作:
for ( i = 0; i < 5 && !found2 ;i++ ){ //this does work as above
found2=strstr( myContacts[i].cFirstName , name);
printf("i %d\n", i);
}
printf("Name found %s", found2);
我想要使用 strstr() 实现此功能,因为现在我可以搜索“Clau”并将其与“Claudia”匹配”。 这比 strcmp() 更能满足我的需求,尽管我很确定也可以使用 strcmp() 来完成它,并且比我更复杂或更好的 C 技能。
再次感谢您的回答!
What am I not getting here?
This works pretty well:
for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
found=strcmp( name, myContacts[i].cFirstName);
printf(" i %d\n", i);
}
printf(" \nName Found %s", myContacts[i-1].cFirstName );
But just out of curiosity, I'm trying to use also strstr().
/*** This achieves the same functionality as above ***/
for ( i = 0; i < 5 ;i++ ){
found2=strstr( myContacts[i].cFirstName , name);
printf(" i %d\n", i);
if (found2 != NULL)
{
printf(" \nName Found %s", myContacts[i].cFirstName );
break;
}
}
This however is not working:
for ( i = 0; i < 5 && found2 != '\0' ;i++ ){ //this does not work as above
for ( i = 0; i < 5 && found2 != NULL ;i++ ){ // this also is not wroking
found2=strstr( myContacts[i].cFirstName , name);
}
printf(" \nName Found %s", myContacts[i].cFirstName );
Thanks in advance for you suggestions.
Full code:
# please take my codes with a grain of skepticism, I am still learning
# i know of sizeof(), but I rather not use it just for the purpose of my exercise
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXBUFFERSIZE 10
typedef struct contact {
char cFirstName[10];
char cLastName[10];
char cTelphone[12];
} address ; // end type
// function prototype
void printContacts( address * );
void printMenu();
char getChoice();
void storeContact( address [] , int *);
//int searchContact( address [] , char * );
void searchContact( address [] , char [] );
int main(){
char cSelection = 0;
address myContacts[5];
char buffer[MAXBUFFERSIZE];
int i ;
// initialize array to be zeros
for ( i = 0; i < 5 ; i++ ){
strcpy(myContacts[i].cFirstName, "0");
strcpy(myContacts[i].cLastName,"0");
strcpy(myContacts[i].cTelphone,"0");
}
strcpy(myContacts[0].cFirstName, "Jonny");
strcpy(myContacts[1].cFirstName, "Julia");
strcpy(myContacts[2].cFirstName, "Claudia");
strcpy(myContacts[3].cFirstName, "Aaron");
strcpy(myContacts[4].cFirstName, "Sebastian");
int iDel = -1 ; // store the position if one deleted
int iCount = 0 ; // counter for position in the array, when
// inserting names.
while ( cSelection != '5' ) {
printMenu();
cSelection = getChoice();
switch (cSelection) {
case '1':
printContacts( myContacts );
break;
case '2':
if ( ( iDel >= -1 ) && ( iCount < 5 ) ){
//printf("\niCount is %d ", iCount);
storeContact( myContacts, &iCount );
iCount++;
//printf("\nOutside storeContact, *Plocation %d", iCount );
}
if ( iCount >= 5 ) {
printf("\nThe Memory is full, consider deleting some"\
"Contacts");
}
break;
case '3':
{
printf("\nEnter a name or part of a name to search:\n");
fscanf(stdin, "%s", buffer);
getchar(); // clear the last enter
printf("\nThe line you entered was:\n");
printf("%s\n", buffer);
searchContact( myContacts, buffer );
break;
}
case '4':
//iDel=deleteContact( myContacts );
break;
}// end of switch
}// end of while
return 0;
} // end main
char getChoice(){
char cSelection = 'q'; //for the menu
/**** always scanf CHARS so you can check
* if digit or char !!! ****/
scanf("%s", &cSelection);
while ( strlen(&cSelection) != 1 ){
printf("\nChoich not understood, enter a number again:");
scanf("%s",&cSelection);
}
if ( isalpha(cSelection) ){
printf( "You entered a letter of the alphabet\n" );
cSelection = -1;
printf( "Illegal choice !!!" );
}
return cSelection;
}
void printContacts( address * myContacts ){
int i ;
for ( i = 0; strcmp(myContacts[i].cFirstName,"0") != 0 && i < 5 ; i++ ){
printf("\nmyContacts[%d].cFirstName: %s", i, \
myContacts[i].cFirstName );
}// end for
}
void printMenu(){
printf("\n\n\tSilly Phone Book\n\n");
printf("\n\n1\tPrint Phone Book\n");
printf("2\tAdd New Contact\n");
printf("3\tSearch For Contact\n");
printf("4\tDelete Contact\n");
printf("5\tQuit\n");
printf("\nSelect Action: ");
}
//void storeContact( address myContacts[] ){ //syntactic sugar
void storeContact( address * myContacts, int *Plocation ){
char ch; /* handles user input */
char buffer[MAXBUFFERSIZE]; /* sufficient to handle one line */
int x = 0;
x=*Plocation;
ch = getchar(); // clear the last enter
printf("Enter a name (<10 characters)\n");
//ch = getchar();
//char_count = 0;
//while( (ch != '\n') && (ch != EOF ) && (char_count < MAXBUFFERSIZE)) {
//buffer[char_count++] = ch;
//ch = getchar();
//}
//buffer[char_count] = 0x00; /* null terminate buffer */
//fgets(buffer,11,stdin);
fscanf(stdin, "%s", buffer); /* read from keyboard */
printf("\nThe line you entered was:\n");
printf("%s\n", buffer);
//TODO: add check that string is not too long!!!
// if we do that, the code won't blow here ?
strcpy(myContacts[x].cFirstName, buffer);
}
//int searchContact( address * myContacts, char name[] ){
void searchContact( address * myContacts, char * name ){
int found;
char *found2;
//printf("\nHey dude im buffer from inside searchContact: %s", name);
// iterate throught the array, print possible matches
int i = 0;
//for ( i = 0; i < 5 && found != 0 ;i++ ){
//for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
//found=strcmp( name, myContacts[i].cFirstName);
//printf(" i %d\n", i);
//}
//printf(" \nName Found %s", myContacts[i-1].cFirstName );
/*** This achieves the same functionality as above
for ( i = 0; i < 5 ;i++ ){
found2=strstr( myContacts[i].cFirstName , name);
printf(" i %d\n", i);
if (found2 != NULL)
{
printf(" \nName Found %s", myContacts[i].cFirstName );
break;
}
} ***/
for ( i = 0; i < 5 && &found2 != '\0' ;i++ ){ //this does not work as above
found2=strstr( myContacts[i].cFirstName , name);
printf("found %p i %d\n", found2, i);
//printf(" \nName Found %s", myContacts[i].cFirstName );
}
//return found;
} // end of searchContacts if ( isalpha(cSelection) ){
printf( "You entered a letter of the alphabet\n" );
cSelection = -1;
printf( "Illegal choice !!!" );
}
return cSelection;
}
void printContacts( address * myContacts ){
int i ;
for ( i = 0; strcmp(myContacts[i].cFirstName,"0") != 0 && i < 5 ; i++ ){
printf("\nmyContacts[%d].cFirstName: %s", i, \
myContacts[i].cFirstName );
}// end for
}
void printMenu(){
printf("\n\n\tSilly Phone Book\n\n");
printf("\n\n1\tPrint Phone Book\n");
printf("2\tAdd New Contact\n");
printf("3\tSearch For Contact\n");
printf("4\tDelete Contact\n");
printf("5\tQuit\n");
printf("\nSelect Action: ");
}
//void storeContact( address myContacts[] ){ //syntactic sugar
void storeContact( address * myContacts, int *Plocation ){
char ch; /* handles user input */
char buffer[MAXBUFFERSIZE]; /* sufficient to handle one line */
int x = 0;
x=*Plocation;
ch = getchar(); // clear the last enter
printf("Enter a name (<10 characters)\n");
//ch = getchar();
//char_count = 0;
//while( (ch != '\n') && (ch != EOF ) && (char_count < MAXBUFFERSIZE)) {
//buffer[char_count++] = ch;
//ch = getchar();
//}
//buffer[char_count] = 0x00; /* null terminate buffer */
//fgets(buffer,11,stdin);
fscanf(stdin, "%s", buffer); /* read from keyboard */
printf("\nThe line you entered was:\n");
printf("%s\n", buffer);
//TODO: add check that string is not too long!!!
// if we do that, the code won't blow here ?
strcpy(myContacts[x].cFirstName, buffer);
}
//int searchContact( address * myContacts, char name[] ){
void searchContact( address * myContacts, char * name ){
int found;
char *found2;
//printf("\nHey dude im buffer from inside searchContact: %s", name);
// iterate throught the array, print possible matches
int i = 0;
//for ( i = 0; i < 5 && found != 0 ;i++ ){
//for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
//found=strcmp( name, myContacts[i].cFirstName);
//printf(" i %d\n", i);
//}
//printf(" \nName Found %s", myContacts[i-1].cFirstName );
/*** This achieves the same functionality as above
for ( i = 0; i < 5 ;i++ ){
found2=strstr( myContacts[i].cFirstName , name);
printf(" i %d\n", i);
if (found2 != NULL)
{
printf(" \nName Found %s", myContacts[i].cFirstName );
break;
}
} ***/
for ( i = 0; i < 5 && found2 != '\0' ;i++ ){ //this does not work as above
found2=strstr( myContacts[i].cFirstName , name);
printf("found %p i %d\n", found2, i);
//printf(" \nName Found %s", myContacts[i].cFirstName );
}
//return found;
} // end of searchContacts
Just for the completeness of this discussion, I'm adding what finally really worked as I wanted it.
This came after going through all the answers, so thanks everyone:
I forgot to initialize the pointer:
char *found2=NULL;
Now the following loop works as expected:
for ( i = 0; i < 5 && !found2 ;i++ ){ //this does work as above
found2=strstr( myContacts[i].cFirstName , name);
printf("i %d\n", i);
}
printf("Name found %s", found2);
I wanted this functionallity with strstr() because now I can search "Clau" and match it to "Claudia".
This is better for my needs than strcmp(), although I am quite sure it can be done also with strcmp(), with more sophistication or better skills in C than I have.
Thanks again for the answers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
found2
是一个char *
。您应该编写
for (i = 0; i < 5 && !found2; i++) //etc etc
(或在循环中测试
found2
并中断如果非空)Your
found2
is achar *
.You should write
for (i = 0; i < 5 && !found2; i++) //etc etc
(or test for
found2
in the loop and break if non NULL)不要使用自行车。
通过使用 strstr() 你只需要使用它一次:(
不要忘记相应的 null 检查)
don't use cicles.
By using strstr() you just need to use it once so:
(don't forget the corresponding check for null)
在
for
循环中的条件:您想要检查
found2
是否指向NULL
,正如您甚至提到的那样,所以found2 != NULL
。否则,您会将found2
的地址与 NUL 字符 ('\0'
) 进行比较,这绝对不是您想要的去做。但是,您说
strstr
代码段与strcmp
代码段具有相同的功能也是错误的;两者的功能完全不同。 阅读strstr
的文档。另一件事,在你的第一个片段中
“Name Found”
总是会被打印您的代码还有很多错误,例如:
如果您想将
char
存储在中,则将cSelection
声明为char
它使用格式说明符%c
。如果要读取整个字符串,请将其设为char
array,传递数组地址时不需要&
到一个函数。传递给
strlen
的&cSelection
的敌人相同。出于同样的原因,毫无意义。(f)scanf
对于读取字符串也是不安全的,并且可能导致缓冲区溢出,您应该使用fgets(STRING, SIZE, stdin)
代替。无论如何,只要打开你的编译器警告,这样你就可以捕获以上所有内容。With your condition in the
for
loop:You're wanting to check if
found2
is pointing toNULL
, as you even mention yourself, so make thatfound2 != NULL
. Otherwise you're comparing the address offound2
to the NUL character ('\0'
), which is definitely not what you're wanting to do.However, you're also wrong in saying that the
strstr
snippet has the same functionality as thestrcmp
snippet; the two functions are completely different. Read the documentation forstrstr
.Another thing, in your first snippet
"Name Found"
is always going to be printedThere's also so many more wrong things with your code, such as:
cSelection
is declared as achar
, if you want to store achar
in it use the format specifier%c
. If you want to read in a whole string, make it achar
array, and the&
is unnecessary when passing the address of an array to a function.Same foes for
&cSelection
being passed tostrlen
. Makes no sense for the same reasons.(f)scanf
is also unsafe for reading strings and can cause buffer overflows, you should usefgets(STRING, SIZE, stdin)
instead. Anyway just turn up your compiler warnings so you can catch all of the above.