How to search for names by letters in a string Array? - c

Do anybody knows how to search for a name in a string array? If i register the name 'jacob' and search for cob I need to get jacob shown instead of not showing up anything. I don't know if strcmp is the right way to do it. Any ideas?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
struct name{
char name[MAX];
};
void getRegister(struct name name[], int *nrNames);
void getSearch(struct name name[], int nrNames);
int readLine(char s[], int length);
int main(){
int run=1;
struct name name[MAX];
int nrNames=0;
while(run){
char choice;
printf("\n (1)Register\n(2)Search\n(3)Quit\n");
scanf(" %c%*c", &choice);
if(choice=='1') getRegister(name, &nrNames);
if(choice=='2') getSearch(name, nrNames);
if(choice=='3') run=0;
}
return 0;
}
void getRegister(struct name name[], int *nrNames){
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
(*nrNames)++;
}
void getSearch(struct name name[], int nrNames){
int i;
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
if(i>=0){
printf("Name/s:\n");
for(i=0; i<nrNames;i++){
if(strcmp(input, name[i].name)==0){
printf("\n%s\n",name[i].name);
}
}
}
}
int readLine(char s[], int length){
int ch, i=0;
while(isspace(ch=getchar()));
while(ch!='\n' && ch!=EOF) {
if(i<length) s[i++]=ch;
ch = getchar();
}
s[i]='\0';
return i;
}

Try to search for the match in the array. The code below displays a position for each occurrence of the second array in the first array. It uses naive approach. There are more efficient algorithms like Knuth-Morris-Pratt or Boyer-Moore algorithm.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
int main(){
char c;
char name[MAX], search_name[MAX];
int i = 0, j = 0, match = 0, count = 0;
printf("Register name: ");
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
name[i++] = c;
}
}
name[i] = '\0';
printf("Search name: ");
i = 0;
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
search_name[i++] = c;
}
}
search_name[i] = '\0';
i=-1;
match = 0;
do {
i++;
j = 0;
do {
if (name[i+j] == search_name[j])
match = 1;
else {
match = 0;
break;
}
j++;
} while (search_name[j] != '\0');
if (match)
printf("Match on position %d ", i);
} while (name[i+j] != '\0');
printf("\n");
return 0;
}

I found the soulution myself. Here is the code for those who get stuck as I did.
void searchName(const struct varor reg[], int nrOfGoods){
int i;
char name[20];
printf("Enter name: ");
readLine(name, WORDLENGTH);//gets input
if(i>=0){
printf("\nId.number \t Name \t\t\t Quantity\n");
for(i=0; i<nrOfGoods;i++){
if(strstr(reg[i].name, name)!=NULL){ //this should do the job
printf("%-17d%-24s%-5d\n",reg[i].idnumber,reg[i].name.reg[i].quantity);
}
}
}
}

Related

How can I delete a user inputed element/data from an Array in Structure? [duplicate]

How to delete an element from the array of type structure? Let's say if I register an item and then want to delete it how can I do that? The delete function is at the end of the code. I want to delete the item by giving the varunummer (id number). Any one know how to do it?
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define WORDLENGTH 30
#define MAX 5
struct varor {
int varunummer;
char namn[WORDLENGTH];
int lagersaldo;
};
int readLine(char s[], int length);
int ifVarunummerExist(int varunummer, const struct varor reg[], int nrOfGoods);
void registerVaror(struct varor reg[], int *nrOfGoods);
void getPrint(const struct varor reg[], int nrOfGoods);
void avregristreraVaror(struct varor reg[], int nrOfGoods);
int main(void) {
struct varor vRegister[WORDLENGTH];
int nrOfGoods = 0;
int run = 1;
while (run) {
char choice;
printf("\n\t\tMeny - Lager Program\n\n\
(1) Register\n\b\b\b\b\
(2) Print\n\
(3) Delete\n\
(4) Quit\n");
scanf(" %c%*c", &choice);
if (choice=='1')
registerVaror(vRegister, &nrOfGoods);
if (choice=='2')
getPrint(vRegister, nrOfGoods);
if (choice=='3')
avregristreraVaror(vRegister, nrOfGoods);
else if (choice=='4')
run = 0;
}
return 0;
}
int ifVarunummerExist(int varunummer, const struct varor reg[], int nrOfGoods) {
int i;
for (i = 0; i < nrOfGoods; i++)
if(reg[i].varunummer == varunummer)
return i;
return -1;
}
int readLine(char s[], int length) {
int ch, i=0;
while (isspace(ch=getchar()));
while (ch != '\n' && ch != EOF) {
if (i < length)
s[i++] = ch;
ch = getchar();
}
s[i] = '\0';
return i;
}
void registerVaror(struct varor reg[], int *nrOfGoods) {
char namn[WORDLENGTH], tmp[WORDLENGTH];
int varunummer, lagersaldo;
if (*nrOfGoods == MAX) {
printf("\nError! Finns inte plats kvar!\n");
return;
}
printf("Ange varunummer: ");
scanf("%d", &varunummer);
if (ifVarunummerExist(varunummer, reg, *nrOfGoods) >= 0) {
printf("\nVarunummer finns redan!\n");
return;
}
reg[*nrOfGoods].varunummer = varunummer;
printf("Ange namn: ");
readLine(reg[*nrOfGoods].namn, WORDLENGTH);
printf("Ange lagersaldo :");
scanf("%d", &reg[*nrOfGoods].lagersaldo);
//reg[*nrOfGoods]=createVara(varunummer,namn,lagersaldo);
(*nrOfGoods)++;
}
void getPrint(const struct varor reg[], int nrOfGoods) {
int i;
printf("\nVarunummer \t Namn \t\t\t Lagersaldo\n");
for (i = 0; i < nrOfGoods; i++) {
printf(" %d \t\t %s \t\t\t %d\n",reg[i].varunummer,reg[i].namn,reg[i].lagersaldo);
}
}
void avregristreraVaror(struct varor reg[], int nrOfGoods) {
int run = 1;
while (run) {
char choice;
printf("\n (1) Delete \n (2) Exit");
scanf(" %c", &choice);
//DELETE IF CHOICE 1---------
if (choice == '1') {
int i, varunummer;
printf("Ange varunummer: ");
scanf("%d", &varunummer);
for (i = varunummer + 1; i < MAX; i++) {
reg[i - 1] = reg[i];
}
reg[i] = 0;
}
}
//QUIT TO MY MENU CHOICE 2--------
if (choice == '2')
run = 0;
}
You can try iterating through the array in a for loop UNTIL your varunummer is matched with the struct's property. Something along these lines (let's say you are searching for the member with varunummer = varunummerToLookFor), this shift all the elements in the array from the point onwards of your deletion by 1, hence, producing an array with the same sequence as before but with your wanted element removed. Hope that helps!
for(int i = 0, i < varorArraySize, i++){
if(varunummerToLookFor == varorArray[i].varunummer){
for (i = pos; i < varorArraySize - 1; i++)
{
varorArray[i] = varorArray[i + 1];
}
}
}

Trying to introduce blanks in regular interval in a string

I tried to write a function that inserts space at regular intervals in a string.
If a[50] is a string, and n is the preferred interval from the user,
insert_space(a,b,len,n) will insert blanks after the n'th column and will store the modified string in b.
#include <stdio.h>
int getinput(char temp[]);
void insert_space(char s1[],char s2[],int,int);
int main ()
{
int n, len;
char a[100], b[100];
printf("Enter the nth column number for inserting\n");
scanf("%d",&n);
printf("Enter the line\n");
len=getinput(a);
insert_space(a,b,len,n);
printf("%s\n",b);
}
void insert_space(char s1[],char s2[],int len, int n)
{
int i=0, c=0,flag=0;
for(i=0;i<=len;i++)
{
if(flag!=n)
{
s2[c]=s1[i];
c++;
flag++;
}
else
{
s2[c]=' ';
i=i-1;
c++;
flag=0;
}
}
s2[c]='\0';
}
int getinput(char temp[])
{
int c, i=0;
while((c=getchar())!=EOF)
{
temp[i]=c;
i++;
}
i--;
temp[i]='\0';
return i;
}
I entered the values of the string a as abcdefghijkmnop. Instead of
"abdce fghij kmnop" as the ouput in b, I got "abcd efghi jkmno p" as the output. I'm not sure what I did wrong here.
edit: After just including the insert_function code, I've edited it to include the entire execution code.
There is a \n ,newline (Enter) from scanf("%d",&n); which is recorded as a[0]. So you have to manage this UN-handled newline (Enter).
To solve this, add an extra c = getchar(); before loop while ((c = getchar()) != EOF) in function int getinput(char temp[]), to handle that extra newline left behind by scanf("%d",&n);
Modified code:-
#include <stdio.h>
int getinput(char temp[]);
void insert_space(char s1[], char s2[], int, int);
int main()
{
int n, len;
char a[100], b[100];
printf("Enter the nth column number for inserting\n");
scanf("%d", &n);
printf("Enter the line\n");
len = getinput(a);
insert_space(a, b, len, n);
printf("%s\n", b);
}
void insert_space(char s1[], char s2[], int len, int n)
{
int i = 0, c = 0, flag = 0;
for (i = 0; i <= len; i++)
{
if (flag != n)
{
s2[c] = s1[i];
c++;
flag++;
}
else
{
s2[c] = ' ';
i = i - 1;
c++;
flag = 0;
}
}
s2[c] = '\0';
}
int getinput(char temp[])
{
int c, i = 0;
c = getchar(); // to handle extra newline from scanf
while ((c = getchar()) != EOF)
{
temp[i] = c;
i++;
}
i--;
temp[i] = '\0';
return i;
}
Output :-
Enter the nth column number for inserting
5
Enter the line
abcdefghijkmnop
abcde fghij kmnop

C strcmp segmentation fault

#include <string.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct bank
{
char an;
char name;
char type;
int bal;
};
int main()
{
int i=0,n;
printf("Enter the number of accounts\n");
scanf("%d",&n);
struct bank a[n];
printf("Enter the details of the users\n");
for(i=0;i<n;i++)
{
scanf("%s%s%s%d",a[i].an,a[i].name,a[i].type,&a[i].bal);
}
printf("The details of the users are\n");
for(i=0;i<n;i++)
{printf("%s\n%s\n%s\n%d\n\n",a[i].an,a[i].name,a[i].type,a[i].bal);}
char atype[10];
printf("Enter the type of account you want to search\n");
scanf("%s",atype);
char typ[10];
char s[]="savings";
char c[]="current";
int result,res1,res2;
result = strcmp(atype,s);
if(result == 0)
{
for(i=0;i<n;i++)
{
typ[10] = a[i].type;
res1 = strcmp(typ,s);
if(res1 == 0)
{
printf("%s\n%s\n%s\n%d\n\n",
a[i].an,a[i].name,a[i].type,a[i].bal);
}
printf("\n");
}
} else
{
for(i=0;i<n;i++)
{
typ[10] = a[i].type;
res2 = strcmp(typ,c);
if(res2 == 0)
{
printf("%s\n%s\n%s\n%d\n\n",
a[i].an,a[i].name,a[i].type,a[i].bal);
}
printf("\n");
}
}
}
so basically ik its my homework but i did everythimg and i still cannot resolve the segmentation fault.please help
i think its something to do with strcmp() function but oh well
i checked all the sources but couldnt really find any fix.
any help would be appreciated.
For starters:
This
typ[10] = ...
accesses typ one past its valid memory. This invokes undefined behaviour, so anything can happen from then on.
In C array indexing is 0-based. So for char[10] the highest allowed index would be 9. Access the 1st element would be done by using 0.
You have made 2 mistakes here .
First your struct bank declaration was wrong. You forgot to declare name an and type as string. You declared it as just character(char).It should be like :-
struct bank
{
char an[100]; // assuming 100 is max size of input strings
char name[100];
char type[100];
int bal;
};
second you cannot do typ[10] = a[i].type; you should use strcpy() Something like this :-
strcpy(typ,a[i].type);
So this corrected code will work :-
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct bank // change made 1
{
char an[100];
char name[100];
char type[100];
int bal;
};
int main()
{
int i = 0, n;
printf("Enter the number of accounts\n");
scanf("%d", &n);
struct bank a[n];
printf("Enter the details of the users\n");
for (i = 0; i < n; i++)
{
scanf("%s%s%s%d", a[i].an, a[i].name, a[i].type, &a[i].bal);
}
printf("The details of the users are\n");
for (i = 0; i < n; i++)
{
printf("%s\n%s\n%s\n%d\n\n", a[i].an, a[i].name, a[i].type, a[i].bal);
}
char atype[10];
printf("Enter the type of account you want to search\n");
scanf("%s", atype);
char typ[10];
char s[] = "savings";
char c[] = "current";
int result, res1, res2;
result = strcmp(atype, s);
if (result == 0)
{
for (i = 0; i < n; i++)
{
strcpy(typ,a[i].type); // change made 2
res1 = strcmp(typ, s);
if (res1 == 0)
{
printf("%s\n%s\n%s\n%d\n\n",
a[i].an, a[i].name, a[i].type, a[i].bal);
}
printf("\n");
}
}
else
{
for (i = 0; i < n; i++)
{
strcpy(typ,a[i].type); // change made 3
res2 = strcmp(typ, c);
if (res2 == 0)
{
printf("%s\n%s\n%s\n%d\n\n",
a[i].an, a[i].name, a[i].type, a[i].bal);
}
printf("\n");
}
}
}
So your mistake was not with strcmp()

Error: too few arguments to function 'strcmp'

I am having a few issues with my code. First: when I try to compile, I get error: too few arguments to function 'strcmp'. I have looked all over and made multiple changes and am still unable to get it to work. Second: when my code does compile (if I remove the strcmp part), it will not complete the count functions correctly. Can anyone please assist? Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count(char array[], int size);
int stringLen(char array[]);
int convert(char ch);
int value, n;
int main()
{
//char * str;
//char s;
char a[100];
char b[100];
char c[100];
int charCount = stringLen(a);
int lCount = count(a, charCount);
printf("Enter your string: \n");
scanf("%s \n", a);
printf("Enter your string: \n");
scanf("%s \n", b);
printf("Enter your string: \n");
scanf("%s \n", c);
printf("The count is %d, length is %d\n", lCount, charCount);
int i;
for(i = 0; i < charCount; i++)
{
char c = a[i];
printf("Char %s = %d \n", &c, value);
}
n = strcmp(char string1[], char string2[], char string3[]);
printf("The first string in the alphabet is: %d \n", n);
return 0;
}
int stringLen(char array[])
{
char count;
int index;
while(array[index] !=0)
{
count++;
index++;
}
return count;
}
int count(char array[], int size)
{
int count;
int i;
for(i = 0; i < size; i++)
{
if(array[i] == 'a')
{
count ++;
}
else if(array[i] == 'A')
{
count ++;
}
}
return count;
}
This is not right way to use strcmp.
n = strcmp(char string1[], char string2[], char string3[]);
strcmp is used for compararison of string. See doc
int result = strcmp (string1,string2)
If strings are same, function will return 0.

Arrays in a Palindrome program

So I made a program where I have to input a word and it displays if it is a palindrome (a word that is the same both ways) or not.
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]){
char word;
int length, counter;
printf("Please enter a word: ");
scanf("%c", &word);
int flag = 1;
for (counter = 0; counter < length && flag; counter++) {
printf("%c\t %c", word[counter], word[length - counter])
if (word[counter] == word[length - counter - 1]){
flag = 0;
}
}
if (flag) {
printf("%c is a palindrome!", word);
}
else {
printf("%c is NOT a palindrome!", word);
}
}
I set it up so that it displays each letter side by side. If a letter isn't the same then the flag is "thrown"(set to 0) and this will end the program saying: "word is NOT a palindrome!"
I get an error at the part where it says word[counter] saying it isn't a subscripted value. What can I do to make this work? Is there anything else I am doing wrong?
This char word; is not an array. This char word[100]; is an Array. Also you read a single character using scanf("%c", &word); not a word (as in a string or series of characters). Use:
fgets (word , 100 , stdin)
Also length is not initialized, so it will lead to UB.
Make this modifications in your program.It will run fine.
#include <stdio.h>
#include <string.h>
int main()
{
char word[100];
int length, counter;
printf("Please enter a word: ");
scanf("%s",word);
length=strlen(word);
int flag = 1;
for(counter = 0; counter < length/2 && flag; counter++)
{
if (word[counter] != word[length-counter-1])
{
flag = 0;
break;
}
}
if (flag)
{
printf("%s is a palindrome!\n", word);
}
else {
printf("%s is NOT a palindrome\n!", word);
}
}
****************************************************************
* Simple Array Palindrome Program *
****************************************************************/
#include <iostream>
using namespace std;
int main (){
int arr_size;
int flag=0;
/*****************************************
* Array Size *
*****************************************/
cout<<"Enter The Array Size: \n->arr[";
cin>>arr_size;cout<<" ]";
int arr[arr_size];
/*****************************************
* User_Input *
*****************************************/
for(int i=0;i<arr_size;i++){
cout<<"Enter Value For Arr[ "<<i<<" ] -> ";
cin>>arr[i];
}
/*****************************************
* Palindrome_Check *
*****************************************/
for(int k=0,j=arr_size-1;k<arr_size && j>-1;k++)
{
if(arr[i]==arr[j];
{
flag++;
}
}
/*****************************************
* Flag Check *
*****************************************/
if(flag==arr_size) {
cout<<"Array Is Palindrome: ";
}
else
{
cout<<"Array Is Not Palindrome: ";
}
}

Resources