in C: reading input string, finding it in char array - c

writing another program, it reads a txt file, and stores all the letter characters and spaces (as \0) in a char array, and ignores everything else. this part works.
now what i need it to do is read a user inputted string, and search for that string in the array, then print the word every time it appears. im terrible at I/O in C, how do you read a string then find it in a char array?

#include <stdio.h>
...
char str [80];
printf ("Enter your word: ");
scanf ("%s",str);
char* pch=strstr(fileData,str);
while (pch!=NULL)
{
printf ("found at %d\n",pch-fileData+1);
pch=strstr(pch+1,str);
}

read in the user inputted string as a char array as well (cause strings are basically char* anyway in C)
use a string matching algorithm like Boyer-Moore or Knutt-Morris-Pratt (more popularly known as KMP) - google for it if you like for C implementations of these - cause they're neat, tried and tested ways of searching strings for substrings and pattern matches and all.
for each of these indexOf cases, print the position where the word is found maybe? or if you prefer, the number of occurrences.
Generally, the list of C string functions, found here, say, are of the format str* or strn*, depending on requirements.

One for-loop inside another for-loop (called nested loop). Go through all the letters in your array, and for each letter go through all the letters in your input string and find out if that part of the array matches with the input string. If it does, print it.

Related

How to extract string-only from stdin using Scanf?

I am a beginner of C and trying to extract Characters from standard input.
Input = "C0h1r2i3s4"
Expected Outcome = "Chris"
I've tried two ways to achieve this:
Use scanf to store input in one variable -> traverse through input one character a time -> if that character is not a number in ASCII table, store that character in a variable
Use fgets to get input and store in one variable -> traverse through input one character a time -> if that character is not a number in ASCII table, store character in a variable
I wonder if it's possible to use scanf/fgets to get only the characters from stdin? So that I don't have to traverse through every characters.
I've tried to use scanset below, but it seems scanf always screens at character-level and stops when the next char does not fit specified format.
Anyway, I wonder if there is a more powerful use of scanset & scanf.
Code for scanf()
#include <stdio.h>
#include <stdlib.h>
void main()
{
char str[50];
//intput = C0h1r2i3s4
scanf("%s", &str); // str = "C0h1r2i3s4"
//intput = C0h1r2i3s4
scanf("%*c%*d%s", &str); // str = "h1r2i3s4" -> C & 0 is ignored
//intput = C0h1r2i3s4
scanf("%[A-Z,a-z]%*d%s", &str); // str = "C" -> are they a valid format identifier? "%[A-Z,a-z]%*d%s"
}
Just want to close this question in case someone else is looking for similar one
In C, there is no simple way to extract certain characters directly from stdin.
first, we need to read the complete inputs from stadin
then, we travers through the inputs to decides which characters are in concern
Thank you, the-busybee, for your comment that saved my life earlier this year. I cannot add a comment due to not enough reputation on GitHub, and I just realized that I could reply to my own post.

Can I make a while loop using Char, instead of Double?

I'm new to this, and I'm assuming there is an easy solution to my issue. My first formula works exactly how I'd like it to. If the user input matches dogage99, then it prints "Correct". I want to do something similar, but using words instead of numbers. I've switched double for char, and adjusted the formula accordingly.
The problem is, the second formula doesn't work as I expected. When the user input matches dogname1, it doesn't print "Correct", it just continuously asks to "enter dog name".
What can I do to fix my issue?
int main()
{
double guess99;
double dogage99 = 3;
while (guess99 != dogage99) {
printf ("enter dog age:");
scanf ("%lf", &guess99);
}
printf ("Correct\n");
char guess1;
char dogname1= "spot";
while (guess1 != dogname1) {
printf ("enter dog name:");
scanf ("%s", &dogname1);
}
printf ("Correct\n");
First of all the line
char dogname1= "spot";
should be corrected to
char *dogname1= "spot";
This way the char array dogname1 will be correctly initialized as a character array and will contain the null-terminator "\0" at the end of the array.
You must also ensure, that guess has enough memory secured, so you must either create a array of sufficiently enough bytes (for e.g. 256), or dynamically allocate memory. In this example I would do the first changing char guess1; to char guess1[256];
Knowing that guess1 has sufficiently enough memory and a null-terminator we can next rewrite the while loop to
while(strcmp(guess1, dogname1)) { ... }
The strcmp() standard library function returns 0 if and only if both character arrays match lexicographical and that is also the time we want to go out of the loop. It is also important to know, that you must ensure both arrays have null-terminators when using this exact function. If you cannot ensure it, then use strncmp().
For reference about all the different compare functions and their implications: https://www.ibm.com/docs/en/aix/7.1?topic=s-strcmp-strncmp-strcasecmp-strcasecmp-l-strncasecmp-strncasecmp-l-strcoll-strcoll-l-subroutine
I am sure the compiler is complaining big time at you about
char dogname = "spot";
in c the type char represent a single character not a string. Strings in C are a sequnce of characters followed by a char set to \0. The compiler will set that up for you if you do
char *dogname="spot";
It will allocate 5 bytes , load s,p,o,t,\0 into those bytes and set the dogname variable to point at the first character.
If you want to compare string you have to use the c library function called strcmp - https://man7.org/linux/man-pages/man3/strcmp.3.html.
Alos you need a char array to receive the input. We just say we want 50 characters. Must also tell scanf to not allow more than 50 charaters. Note that I asked for 51 character array to allow for the trailing 0 that must always be present.
so your loop becomes
char guess1[51];
char *dogname1= "spot";
while (guess1 != dogname1) {
printf ("enter dog name:");
scanf ("%50s", guess1);
}
printf ("Correct\n");
note you must #include string.h
check this out https://www.tutorialspoint.com/cprogramming/c_strings.htm

how to read a string

I´m new to programming and I'm still trying to figure out how everything works out but I want to write a string what should be used later on with adding characters, split the text, upper/lower cases and so on. Right now I am stuck on the reading part of the string and this is what I have so far:
int A, str[100];
printf("Write the text you want to use:\n");
char A;
scanf("%c", &A);
When I run the program it just jumps over this part, is it because I just wrote char A instead of str?
There are several things wrong. First of all you are declaring two times A, with two different types - you should get an error there because you can only declare a variable once.
Secondly, you should indeed store the string in str[100], as it is an array (which can store multiple variables, one in each element, therefore 100 in your case). You should also use char arrays, not int. A is also useless in your case because you will store the string in str.
It is better to use fgets for strings, because it is more secure. Also, scanf will stop reading after the first space in your string, which in most cases is not what you want.
This should work, I also added explanations:
printf("Write the text you want to use:\n");
char str[100];
fgets(str,100,stdin); // 100 is the number of characters to store, stdin indicates that you are reading from the standard input, what the user is typing
printf("String: %s",str); // just for verification
Firstly, You have declared the variable "A" first as an integer, and later as a character datatype, this will generate a conflict during compilation. This can be rectified by using different variable names for both.
After that, answer to your problems can be-
Strings are stored as an array of characters of arrays in C, not just by a single char. So you should declare the desired variable to obtain the string from the user as variable_name char[100] and then use this in fgets.
eg:
printf("Enter the input text:\n");
char string[50];
fgets(str,100,stdin); // the max length of string that can be taken is depicted by 50.
printf("Input was: %s",string); // check your string variable contents, mind the %s used to mark string variables in C
You can use the string library of C, which has a lot of advanced functionalities with an easy and simplified syntax. Go through the link, you'll find it much easier than anything else

How to store multiple sets of strings in a character array

I am trying to store a given input number of sets of strings in a 3D character array, but couldn't.
Is it even possible using char arrays or should i use any other concept like data structures......?
int main()
{
int i,j,T,N[10];
char word[10][10][10];
scanf("%d",&T);/* No of test cases*/
for(i=0;i<T;i++)
{
scanf("%d",&N[i]); /*No of strings*/
for(j=0;j<N[i];j++)
scanf("%s",word[i][j]); /* reading the strings*/
}
return 0;
First: a "3D character array" is better thought of as a "2D string matrix" in this case.
And yes, of course it's very possible.
There are some weaknesses with your code that might trip it up, hard to say since you don't show a full test case with the input data you provide.
scanf() can fail, in which case you cannot rely on the variables having values
scanf() with %s will stop on the first whitespace character, which might cause your scanning code to become very confused
You don't limit the size of string you scan, but only provide 10 bytes of buffer space per string, so easy to get buffer overruns.
A better solution would be to check that the scanning succeeded, and make each string be on a line on its own, and read full lines using fgets() into an appropriately-sized buffer, then perhaps copy the part you want to keep into place in the matrix.

Asking for a name and returning the length of the name in C

I've been struggling with this code for quite some time now.
This is my first time posting here. I am new to C, and I feel that I almost got it.
I have to ask for your name, middle initial, and last name. Then I greet you and tell you the length of your name. Sounds simple enough. I have the following code, I have to use the header file as it is here and that makes things worse. Any help would be greatly appreciated, I feel that I already applied all my knowledge to it and still can't get it to work.
This is my header file:
#ifndef NAME_H_
#define NAME_H_
struct name{
char first[20];
char middle;
char last[20];
};
#endif
and this is my .c file:
#include "name.h"
#include <stdio.h>
#define nl printf("\n");
int strlen(char*s);
char first;
char middle;
char last;
main()
{
printf("enter your first name : ");
scanf("%c", &first);
printf("\n enter your middle initial name : ");
scanf("%c", &middle);
printf("\n enter your last name: ");
scanf("%c", &last);
printf("\n\n Hello %c",first, " %c" ,middle, " %c", last);
printf("\n The String returned the following length: ",strlen);
}
I have t use printf and scanf, then store the name components a name "structure" imported from name.h and lastly use int strlen(char *s); to calculate it.
I get this output with the weird indentation and everything:
enter your first name : Joe
enter your middle initial name :
enter your last name:
Hello J
The String returned the following length: [-my user id]$
Thanks!
Several things about this are not quite right.
First, you shouldn't be declaring strlen yourself. It's a standard C library function, which means you should include the appropriate header. In this case,
#include <string.h>
Second, you're storing the input in variables of type char. Those are literally what they say: they store a single character. So unless you're only allowing people to have single-character names, you need a bit more than that. This sort of string input problem is actually rather tricky in C, since you have to do explicit memory management and don't know how much data the user is going to send you in advance. One of the simpler things is to just use a large buffer and truncate, but for a more complex program you'd want to do error handling and possibly dynamically resize the buffer. But for starters:
char first[1024];
char middle[1024];
char last[1024];
will at least get you started. Your struct name has some of this, but you're not currently using it (and the sizes are pretty small).
Next, scanf is a tricky way to get input strings. scanf of a %s pattern will happily read more than 1024 characters and write over the end of the buffer and destroy your program. This is why C programmers usually read input data using fgets instead, since then you can more easily say how big of a buffer you're willing to read:
fgets(first, sizeof(first), stdin);
Be aware that if the user enters more than 1023 characters, it will read the first 1023 characters and then leave the rest there, where you'll end up reading it as part of the middle name. String handling in C is complex! C is not good at this sort of thing; that's why people tend to use Perl or similar languages for this sort of interactive string handling where you don't know sizes in advance. In C, you have to pursue a strategy like repeatedly calling fgets until you get a newline at the end of the result and then deciding whether to dynamically resize your data structure or throw an error. Alternately, you can use scanf with %1023s but you need to qualify the format to specify the maximum length. The syntax is a bit weird and tricky; fgets is simpler when you're reading character strings.
As mentioned in the other answer, strlen is a function that you need to call on a char * variable (or char array) to get the length of the string it holds. You probably want to call it on first, middle, and last and add them together.
Finally, in your last printf, you have to pass one format and then all of the arguments for that format. You want something more like:
printf("\n\n Hello %s %s %s", first, middle, last);
(once you fix the type of those variables).
This is a lot of random detail. I hope it helps some. The important brief takeaway is that a string in C is a sequence of char ending in a char with a value of 0, and all C data structures have to be sized in advance (either statically or dynamically with malloc). C furthermore has no bounds checking, so it's completely up to you to ensure that you only read as much data as you created space for.
use
strlen(first)
to get the length of variable first ..similarly for other varibles... To get the cumulative length use
printf("\n Length: ",strlen(first)+strlen(middle)+strlen(last));

Resources