Finding words with the same first character - c

I've made an array and now I'm trying to compare first symbols of two strings and if it's true to print that word. But I got a problem:
Incompatible types in assignmentof "int" to "char"[20]"
Here is the code:
for ( wordmas= 0; i < character; i++ )
{
do {
if (!strncmp(wordmas[i], character, 1)
}
puts (wordmas[i]);
}
Maybe you guys could help me?

There are several issues with your code:
You do not need strncmp to compare the first character - all you need is a simple == or !=.
Using a do without a while is a syntax error; you do not need a nested loop to solve your problem.
character is used to limit the progress of i in the outer loop, and also to compare to the first character of a word in wordmas[i]. This is very likely a mistake.
Assuming that wordmas is an array, assigning to wordmas in the loop header is wrong.
The code to look for words that start in a specific character should look like this:
char wordmas[20][20];
... // read 20 words into wordmas
char ch = 'a'; // Look for all words that start in 'a'
// Go through the 20 words in an array
for (int i = 0 ; i != 20 ; i++) {
// Compare the first characters
if (wordmas[i][0] == ch) {
... // The word wordmas[i] starts in 'a'
}
}

Related

C dealing with variable length string

I'm new to C, taking a university course.
In one of the tasks I'm given, I deal with strings. I take strings either entered by user or parsed from a file and then use a function on them to produce an answer (if a specific quality exists).
The string can be of variable length but it is acceptable to assume that their maximum length is 80 characters.
I created the program using a
char s[81];
and then filling up the same array with the different strings each time.
Since the string has to be null-terminated I just added a '\0' at index 80;
s[80] = '\0';
But then I got all kind of weird behaviors - Unrelated characters at the end of the string I entered. I assumed this is because there was space between the end of the 'real' characters and the '\0' character filled with garbage(?).
So what I did is I created a function:
void clean_string(char s[], int string_size) {
int index = 0;
while(index < string_size) {
s[index++] = '\0';
}
}
What I call clean, is just filling a string up with zero characters. I do this every time I am done dealing with a string and ready to accept a new one. Then I fill up the string again character by character and when ever I'll stop, the following character will be a '\0' for sure.
To not include any magic numbers in code (81 each time I call clean_string) I used the following:
#define STRING_LENGTH 81
That works for me. The strings show no strange behavior. But I wondered if this is considered bad practice. Are there problems with this approach?
Just emphasizing, I'm not asking for help in the assignment itself, but tips on how to approach these kind of situations better.
Rather than prefilling the entire array with zeros, it should be simple to just add a single zero after you've read all relevant characters.
For example:
char s[STRING_LENGTH];
int c;
int idx = 0;
while (((c = getchar()) != '\n') && (idx < STRING_LENGTH - 1) && (c != EOF)) {
s[idx++] = c;
}
s[idx] = 0;

Converting Character Array to Integer Array in C for ISBN Validation

I really hope someone can give a well explained example. I've been searching everywhere but can't find a proper solution.
I am taking an introduction to C Programming class, and our last assignment is to write a program which validates a 10 digit ISBN with dashes... The ISBN is inputted as a string in a CHAR array. From there I need to separate each digit and convert them into an integer, so I can calculated the validity of the ISBN. On top of that, the dashes need to be ignored..
My thought process was to create an INT array and then use a loop to store each character into the array, and pass it through the atoi() function. I also tried using an IF statement to check each part of the CHAR array to see if it found a dash. If it did find one, it would skip to the next spot in the array. It looked something like this:
int num[12], i = 0, j = 0, count = 0;
char isbn[12];
printf ("Enter an ISBN to validate: ");
scanf ("%13[0-9Xx-]%*c", &isbn);
do {
if (isbn[i] == '-') {
i++;
j++;
}
else {
num[i]= atoi(isbn[j]);
i++;
j++;
}
count++;
} while (count != 10);
But that creates a segmentation fault, so I can't even tell if my IF statement has actually filtered the dashes....
If someone could try and solve this I'd really appreciate that. The Assignment was due Dec 4th, however I got an extension until Dec 7th, so I'm pressed for time.
Please write out the code in your explanation. I'm a visual learner, and need to see step by step.
There's obviously a lot more that needs to be coded, but I can't move ahead until I get over this obstacle.
Thanks in advance!
First of all, your definition of isbn is not sufficient to hold 13 characters; it should therefore be 14 chars long (to also store the terminating '\0').
Second, your loop is overly complicated; three loop variables that maintain the same value is redundant.
Third, the loop is not safe, because a string might be as short as one character, but your code happily loops 10 times.
Lastly, converting a char that holds the ascii value of a digit can be converted by simply subtracting '0' from it.
This is the code after above improvements have been made.
#include <stdio.h>
int main(void)
{
int num[14], i;
char isbn[14], *p;
printf("Enter an ISBN to validate: ");
scanf("%13[0-9Xx-]%*c", &isbn);
// p iterates over each character of isbn
// *p evaluates the value of each character
// the loop stops when the end-of-string is reached, i.e. '\0'
for (p = isbn, i = 0; *p; ++p) {
if (*p == '-' || *p == 'X' || *p == 'x') {
continue;
}
// it's definitely a digit now
num[i++] = *p - '0';
}
// post: i holds number of digits in num
// post: num[x] is the digit value, for 0 <= x < i
return 0;
}

Simple C If Statement

I made a very simple C program that is supposed to count how many characters and words are in a string (I count words by checking how many spaces are in the text and one to it). The current code is the following (with no 'printf's to keep it shorter):
int main(int argc, char *argv[])
{
int character;
int words, characters = 0;
while ((character = getchar()) != '\n') {
characters = ++characters;
if ((character == ' ') || (character == '\d')) {
words = ++words;
}
}
return 0;
}
My problem is that counting words do not work. I get an accurate count for characters, but words always gives me 2293576, and I cannot for the world figure out why.
Can someone solve this mystery for me?
Thank you for all your answers; I really appreciate the help.
and sorry if my primitive skills made some of your heads hurt. I am a beginner but hopefully improve fast.
You haven't initialized words. Uninitialized local variables in C default to an undefined value and are not automatically initialized to zero.
The statement
int x, y = 0;
Is not the same as
int x = 0, y = 0;
You don't initialize words to 0. Also, change this:
characters = ++characters;
to just:
characters++;
(and for words too).
Also, what is the '\d' character (besides a plain old d)?
You fail to initialize "words". In the statement:
int words, characters = 0;
characters is assigned to 0, but words is left unintialized so it could contain any integer value. The rest of your code then modifies words in its unintialized state. Instead of starting at 0 and counting up, words is starting at something like 2293576 and counting up from there. To fix your code assign words to 0 as well as characters before using them in the for loop.
int words = 0, characters = 0;

Using "strcmp" on specific members of a character array in c

I have a binary search function I am passing a pointer character array, the length of that array, a search pointer character array and another counter for something else.
int binarySearch(char* charArray, int len, char* searchItem, int counter)
{
int position;
int begin = 0;
int end = len-1;
int cond =0;
while(begin <= end)
{
position = (begin + end)/2;
// searchItem is a pointer array and the value I want to compare to is
// at the index of counter (determined outside of this function)
if((cond = strcmp(&charArray[position], &searchItem[counter])) == 0)
{
return position;
}
else if(cond < 0){
begin = position + 1;
}
else
end = position - 1;
}
return -1;
}
From here, going through the code by hand seems to make me want to think it should work fine, however it doesn't. I think I'm getting thrown off somewhere along the lines of my pointers and how I'm referring to them so the wrong data is being compared.
I've looked at it for too long now... really need some help here.
It is not very clear what is being searched in what. But I'm guessing that you are searching for a character in a sorted character array. If that is the case, you can't use a strcmp. Instead you can do:
if(cond = (charArray[position] - *searchItem) == 0)
strcmp assumes that the strings being compared are zero-terminated, and exactly equal length. Therefore, strlen(&charArray[position]) has to equal strlen(&searchItem[counter]). That means position == strlen(&charArray[0]) - strlen(&searchItem[counter]). You don't need to search at all. Either the suffix of charArray matches or it doesn't.
But that's probably not what you intended. What are you trying to achieve?
Are the strings to be compared all of the exact same length? Your code is assuming so. If not, you'll want to use strncmp( ), not strcmp().
strcmp compares all the characters in a char* up to the trailing '\0' character. So you cannot compare single characters (basically you always need two, the character and the trailing '\0') and you cannot compare parts of a string unless you insert a '\0' at the location up to which you want to perform the comparison.
Just for clarity, properly zero terminated strings (last character is '\0') are important for strcmp. strcmp compares two character arrays from the start up to the '\0' character and returns an appropriate comparison value (<0, =0, >0). And of course, both character arrays have to be the same length.
If these are ASCII strings and should be sorted in alphabetic order, I believe it should be
else if(cond < 0){
end = position - 1;
}
else
begin = position + 1;
}
I'm not certain how you wish to sort them though?

Trying to convert morse code to english. struggling

I'm trying to create a function to read Morse code from one file, convert it to English text, print the converted text to the terminal, and write it to an output file. Here's a rough start...
#define TOTAL_MORSE 91
#define MORSE_LEN 6
void
morse_to_english(FILE* inputFile, FILE* outputFile, char morseStrings[TOTAL_MORSE][MORSE_LEN])
{ int i = 0, compare = 0;
char convert[MORSE_LEN] = {'\0'}, *buffer = '\0';
//read in a line of morse string from file
// fgets(buffer, //then what?
while(((convert[i] = fgetc(inputFile)) != ' ') && (i < (MORSE_LEN - 1)))
{ i++;
}
if (convert[i + 1] == ' ')
convert[i + 1] = '\0';
//compare read-in string w/morseStrings
for (i = 48, compare = strcmp(convert, morseStrings[i]); //48 is '0'
i < (TOTAL_MORSE - 1) && compare != 0;
i++)
{ compare = strcmp(convert, morseStrings[i]);
}
printf("%c", (char)i);
}
I have initialized morseStrings to the morse code.
That's my function right now. It does not work, and I'm not really sure what approach to take.
My original algorithm plan was something like this:
1. Scan Morse code in from file, character by character, until a space is reached
1.1 save to a temporary buffer (convert)
2. loop while i < 91 && compare != 0
compare = strcmp(convert, morseString[i])
3. if (test ==0) print ("%c", i);
4. loop through this until eof
but.. I can't seem to think of a good way to test if the next char in the file is a space. So this has made it very difficult for me.
I got pretty frustrated and googled for ideas, and found a suggestion to use this algorithm
Read a line
Loop
-strchr() for a SPACE or EOL
-copy characters before the space to another string
-Use strcmp() and loop to find the letter
-Test the next character for SPACE.
-If so, output another space
-Skip to next morse character
List item
Endloop
But, this loops is kind of confusing. I would use fgets() (I think), but I don't know what to put in the length argument.
Anyways, I'm tired and frustrated. I would appreciate any help or insight for this problem. I can provide more code if necessary.
Your original plan looks fine. You're off by 1 when you check for the ' ' in the buffer, though. It's at convert[i], not convert[i + 1]. The i++ inside the loop doesn't happen when a space is detected.
I wouldn't use strchr(), to complicated.
Loop through the Inputfile reading a line
tokenize line with [strtok][1]
loop through tokens and save(best append) the single Letters to a Buffer
close looops and print
a bit of pseudocode for u
while(there is a next line){
tokens = strtok(line);
int i = 0;
while(tokens hasnext){
save to buffer}}
If you are concerned about the CPU time you can write a lookup table to find the values, something as a switch like this:
case '.-': code = "A"; break;
case '-...': code = "B"; break;
case '-.-.': code = "C"; break;
After you split the morse code by the spaces and send the diferent . and - combinations to the switch to get the original character.
I hope this help.
Best regards.

Resources