comparing characters of a string with constant characters doesn't work - c

I am trying to calculate the number of sentences inside any text on the basis that the end of each sentence may be !, ? or ., but when I used strcmp() it doesn't work as expected. so if the text contains ! and compared with character constant ! it doesn't give the correct output as 0 as assumed.
Although, I tried to test the outputs to understand what took place led to such result but I couldn't understand so can anyone help ?
Thank you.
here is my code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int count_sentences(string text);
int main(void)
{
string text = get_string("text: ");
//printf("%s\n", text);
count_sentences(text);
//printf("%i\n", strcmp("!", "!"));
}
int count_sentences(string text)
{
int string_length = strlen(text);
int num_of_sentences = 0;
const char sent_ind1 = '?';
const char sent_ind2 = '!';
const char sent_ind3 = '.';
//printf("%c %c %c", sent_ind1, sent_ind2,
//sent_ind3);
for (int i = 0; i < string_length; i++)
{
int value1 = strcmp(&text[i], &sent_ind1);
int value2 = strcmp(&text[i], &sent_ind2);
int value3 = strcmp(&text[i], &sent_ind3);
if (value1 == 0 || value2 == 0 || value3 == 0)
{
num_of_sentences += 1;
}
//printf("1- %i 2- %i 3- %i i- %c c- %c si0 %c si1 %c si2 %c\n",
//value1, value2, value3, i, text[i], sent_ind1, sent_ind2,
//sent_ind3);
//printf("1- %i 2- %i 3- %i i- %i\n",
//sent_ind1, sent_ind2, sent_ind3, text[i]);
}
//printf("string length equal %i and number of sentences equal %i.\n",
//string_length, num_of_sentences);
return num_of_sentences;
}

These records
int value1 = strcmp(&text[i], &sent_ind1);
int value2 = strcmp(&text[i], &sent_ind2);
int value3 = strcmp(&text[i], &sent_ind3);
does not make a sense. For starters the second arguments of the calls of strcmp do not point to strings.
Secondly even if they would point to strings the result of the calls will be equal to 0 only in one case when these characters '!', '?' and '.' are the last characters of the string text.
Instead of the function strcmp use functions strcspn and strspn.
For example the function can look the following way
#include <stdio.h>
#include <string.h>
size_t count_sentences( const char *text )
{
size_t n = 0;
const char *end_of_sentence = "!?.";
while ( ( text += strcspn( text, end_of_sentence ) ), *text != '\0' )
{
++n;
text += strspn( text, end_of_sentence );
}
return n;
}
int main( void )
{
const char *text = "Do you know C string functions? "
"Learn them!!! "
"They are useful.";
printf( "%zu\n", count_sentences( text ) );
}
The program output is
3

If you simply want to count a number of '!', '?' and '.' in the string you need to compare characters.
size_t count_sentences(string text)
{
size_t nos = 0;
size_t pos = 0;
while(text[pos])
{
if(text[pos] == '!' || text[pos] == '?' || text[pos] == '.') nos++;
pos++;
}
return nos;
}
strcmp compares the whole strings not looking for the substring in the string. In your case, you do not pass as a second parameter the string only the reference to single char (and it is not a valid string). It is an UB.

In addition to properly comparing a char with a char of a string answered elsewhere, consider a different way to count sentences.
How many sentences in these 2 strings?
No end punctuation
Screaming text!!! What???
To get 1 and 2 rather than 0 and 6. use ".?!" to enable an increment the next time a letter is seen.
size_t count_sentences1(const char *text) {
// Best to use unsigned char for is...()
const unsigned char *utext = (const unsigned char *) text;
size_t num_of_sentences = 0;
int start_of_sentence = 1;
while (*utext) {
if (isalpha(*utext)) {
num_of_sentences += start_of_sentence;
start_of_sentence = 0;
} else if (strchr(".?!", *utext)) {
start_of_sentence = 1;
}
utext++;
}
return num_of_sentences;
}

There are some 'clever' answers regarding "counting punctuation marks." Sadly, these would give an incorrect count when a sentence ends with an 'ellipse' ("...") or what some refer to as an "interobang" ("?!").
Without your CS50 library to test, I've a get_string() that returns a string complete with its trailing newline. This is 'optional' and needs to be adapted for your version of get_string().
// #include <cs50.h> // Don't have
#include <stdio.h>
#include <string.h>
int main() {
char *foo = get_string( "Enter several sentences: " );
foo[strlen(foo)-1] = '\0'; // Chop '\n' off if required
int count = 0;
while( strtok( foo, "?.!" ) )
count++, foo = NULL;
printf( "Number of sentences: %i.\n", count );
return 0;
}
Output:
Enter several sentences: Does. this! fulfill the? requirement????
Number of sentences: 4.

Related

Counting Characters and Strings n C

This is one of the assignments for my class and this is the objective of the assignment:
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1. You may assume that the string does not contain spaces and will always contain less than 50 characters.
This is the code I have so far and I am new to C programming so I don't know how to declare Strings correctly just yet. So far I learned there are no strings in C like there is in Java and you have to do them as a character array:
#include <stdio.h>
#include <string.h>
int main(void) {
char userChar;
char userString[50];
int count = 0;
for (int i = 0; i < userChar; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d", count);
if (count != 1)
printf("'s");
return 0;
}
For example, if I wanted to input n Monday and output 1 n
What would I need to change in my code to go from n Monday to 1 n
This is the only output I am getting, and it only has outputted one thing correctly:
0's
First, I hope this is not considered cheating :-)
Second, you need to define userChar and userString as arguments for main, and pass them in at run time. They are assigned nothing, so that is why you get
0's
Third, your for condition is wrong. You need this so it only iterates through the length of the string:
for (int i = 0; i < strlen(userString); i++)
Finally, You are not printing the value of userChar prior to the return
At first you need to input a string and a character. To count the number of occurrences of the character in the string you can use standard string function strchr.
The program can look something like the following
#include <stdio.h>
#include <string.h>
int main(void)
{
char userChar = ' ';
char userString[50] = "";
printf( "Enter a string without embedded spaces\nof the length less than %d: ", 50 );
scanf( "%49s", userString );
printf( "Enter a character to search in the string: " );
scanf( " %c", &userChar );
size_t n = 0;
for ( const char *p = userString; ( p = strchr( p, userChar ) ) != NULL; ++p )
{
++n;
}
printf( "%zu%s %c\n", n, n < 2 ? "" : "'s", userChar );
}
The expected output is not 0's, it should include the counted character: for example if the character is n and the string Monday, the output should be
1 n
and if the string is Eeny-meeny-miny-moe, the output would be
3 n's
Here is a modified version:
#include <stdio.h>
int main() {
char userChar;
char userString[50];
int i, count;
printf("Enter character: ");
scanf(" %c", &userChar);
printf("Enter string (single word): ");
// read a word with at most 49 characters
scanf(" %49s", userString);
count = 0;
for (i = 0; userString[i] != '\0'; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d %c", count, userChar);
if (count != 1)
printf("'s");
printf("\n");
return 0;
}

How to detect null values (and replace them) when reading from a file using sscanf [duplicate]

I am currently trying to parse UnicodeData.txt with this format: ftp://ftp.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.html However, I am hitting a problem in that when I try to read, say a line like the following.
something;123D;;LINE TABULATION;
I try to get the data from the fields by code such as the following. The problem is that fields[3] is not getting filled in, and scanf is returning 2. in is the current line.
char fields[4][256];
sscanf(in, "%[^;];%[^;];%[^;];%[^;];%[^;];",
fields[0], fields[1], fields[2], fields[3]);
I know this is the correct implementation of scanf(), but is there a way to get this to work, short of making my own scanf()?
scanf does not handle "empty" fields. So you will have to parse it on your own.
The following solution is:
fast, as it uses strchr rather than the quite slow sscanf
flexible, as it will detect an arbitrary number of fields, up to a given maximum.
The function parse extracts fields from the input str, separated by semi-colons. Four semi-colons give five fields, some or all of which can be blank. No provision is made for escaping the semi-colons.
#include <stdio.h>
#include <string.h>
static int parse(char *str, char *out[], int max_num) {
int num = 0;
out[num++] = str;
while (num < max_num && str && (str = strchr(str, ';'))) {
*str = 0; // nul-terminate previous field
out[num++] = ++str; // save start of next field
}
return num;
}
int main(void) {
char test[] = "something;123D;;LINE TABULATION;";
char *field[99];
int num = parse(test, field, 99);
int i;
for (i = 0; i < num; i++)
printf("[%s]", field[i]);
printf("\n");
return 0;
}
The output of this test program is:
[something][123D][][LINE TABULATION][]
Update: A slightly shorter version, which doesn't require an extra array to store the start of each substring, is:
#include <stdio.h>
#include <string.h>
static int replaceSemicolonsWithNuls(char *p) {
int num = 0;
while ((p = strchr(p, ';'))) {
*p++ = 0;
num++;
}
return num;
}
int main(void) {
char test[] = "something;123D;;LINE TABULATION;";
int num = replaceSemicolonsWithNuls(test);
int i;
char *p = test;
for (i = 0; i < num; i++, p += strlen(p) + 1)
printf("[%s]", p);
printf("\n");
return 0;
}
Just in case you would like to consider this following alternative, using scanfs and "%n" format-specifier, used for reading in how many characters have been read by far, into an integer:
#include <stdio.h>
#define N 4
int main( ){
char * str = "something;123D;;LINE TABULATION;";
char * wanderer = str;
char fields[N][256] = { 0 };
int n;
for ( int i = 0; i < N; i++ ) {
n = 0;
printf( "%d ", sscanf( wanderer, "%255[^;]%n", fields[i], &n ) );
wanderer += n + 1;
}
putchar( 10 );
for ( int i = 0; i < N; i++ )
printf( "%d: %s\n", i, fields[i] );
getchar( );
return 0;
}
On every cycle, it reads maximum of 255 characters into the corresponding fields[i], until it encounters a delimiter semicolon ;. After reading them, it reads in how many characters it had read, into the n, which had been zeroed (oh my...) beforehand.
It increases the pointer that points to the string by the amount of characters read, plus one for the delimiter semicolon.
printf for the return value of sscanf, and the printing of the result is just for demonstration purposes. You can see the code working on http://codepad.org/kae8smPF without the getchar(); and with for declaration moved outside for C90 compliance.
I don't think sscanf will do what you need: sscanf format %[^;] will match a non-empty sequence of not-semicolon characters. The alternative would be using readline with the separator being ';', like:
#include <iostream>
#include <sstream>
#include <string>
int main() {
using namespace std;
istringstream i { "something;123D;;LINE TABULATION;\nsomething;123D;;LINE TABULATION;\nsomething;123D;;LINE TABULATION;\n" };
string a, b, c, d, newline;
while( getline(i, a, ';') && getline(i, b, ';') && getline(i, c, ';') && getline (i, d, ';') && getline(i, newline) )
cout << d << ',' << c << '-' << b << ':' << a << endl;
}
(I have only seen you took the c++ tag off this question now, if your problem is c-only, I have another solution, below:)
#include <string.h>
#include <stdio.h>
int main() {
typedef char buffer[2048];
buffer line;
while( fgets(line, sizeof(line), stdin) > 0 ) {
printf("(%s)\n", line);
char *end = line;
char *s1 = *end == ';' ? (*end = '\0'), end++ : strtok_r(end, ";", &end);
char *s2 = *end == ';' ? (*end = '\0'), end++ : strtok_r(end, ";", &end);
char *s3 = *end == ';' ? (*end = '\0'), end++ : strtok_r(end, ";", &end);
char *s4 = *end == ';' ? (*end = '\0'), end++ : strtok_r(end, ";", &end);
printf("[%s][%s][%s][%s]\n", s4, s3, s2, s1);
}
}

Find the length of the longest word in a string. C language

Problem: I can't seem to get my test case 4 to work.
Question:
Write a C function that accepts an English sentence as a parameter, and returns the length of the longest word in the sentence. For example, if the sentence is "I am Tim.", then the length of the longest word "time" in sentence 3 will be returned.
Test Case 1:
Enter a string: I am lee.
longWordLength(): 3
Test Case 2:
Enter a string: There are two disciples in the class.
longWordLength(): 9
Test Case 3:
Enter a string: Good night!
longWordLength(): 5
Test Case 4:
Enter a string: Jovial
longWordLength(): 6
This is the code I have so far:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int longWordLength(char *s);
int main()
{
char str[80], *p;
printf("Enter a string: \n");
fgets(str, 80, stdin);
if (p=strchr(str,'\n')) *p = '\0';
printf("longWordLength(): %d\n", longWordLength(str));
return 0;
}
int longWordLength(char *s)
{
int i, count, max;
max = 0;
count = 0;
while( *(s) != '\0' )
{
if ( *(s) != '\0' && *(s) != ' ' && *(s) != '.' )
{
count++;
printf("current count is %d\n", count);
}
else
{
if(count>max)
{
max = count;
printf("There is a new max! It is %d\n", max);
count = 0;
}
count = 0;
printf("count is resetted!\n");
}
s++;
printf("reach the end of the while loop\n");
}
printf("current max outside while loop is: %d\n", max);
printf("exited\n");
return max;
}
Problem:
Your code does not work when the key word is at the end of a line.
That is because your max is updated inside that while loop and the while loop terminates when the null character is found. Since the null character is always appended to the end of your input string, the last word in a string does not contribute to the output. In this edge case, the loop does not give a chance to execute that else block in the final iteration.
In fact, your code will pass only Test Case 2 because all other cases contain the key word at the end of the input string.
Solution:
Even if you rectify that, your code may still fail if the sentence contains a punctuation mark other than the period.
For example: "Test Case!"
The new code will count "Case!" as a word of length 5 which is greater than the length of "Test" or "Case", and give a wrong answer.
You may look into some library functions that C has to offer in order to help you pass all edge cases.
If you need more assistance, I have made the required modifications to your code:
while( *(s) != '\0' )
{
// if ( *(s) != '\0' && *(s) != ' ' && *(s) != '.' )
// Why check the null character again?
// Spaces and period will not be the only punctuation marks
// You can check for all punctuation marks using ispunct() from <ctype.h>
if (!isspace(*s) && !ispunct(*s))
{
count++;
printf("current count is %d\n", count);
// You can update max here
if(count > max)
{
max = count;
printf("There is a new max! It is %d\n", max);
}
}
/*
Now you can eliminate this block of code
else
{
if(count>max)
{
max = count;
printf("There is a new max! It is %d\n", max);
count = 0;
}
count = 0;
printf("count is resetted!\n");
}
*/
// You can reset count after all that
else
{
count = 0;
printf("count is resetted!\n");
}
s++;
printf("reach the end of the while loop\n");
}
The code assumes that the input will be a proper English sentence.
P. S. This answer earned me the 1K reputation :)
For starters the function parameter should be declared with the qualifier const because within the function the passed string is not being changed. And the function return type should be size_t. It is the return type of the function strlen or the type of the value returned by the sizeof operator.
size_t longWordLength( const char *s);
The last word of a string does not take part in the calculation of the maximum word because the loop stops its iterations as soon as the next character is the terminating zero character '\0'.
It will be a bad idea to process the size of the last word outside the loop. All processing should be done within the loop.
Also your function does not take into account punctuation characters except the point.
For example for a sentence like this "How are you?" your function will give incorrect result.
Instead of checking each character whether it is for example a blank or not you could use standard C functions like strspn and strcspn.
Here is a demonstrative program that shows how the function can be implemented.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
size_t longWordLength( const char *s )
{
const char *delim = " \t";
size_t max = 0;
while ( *s )
{
s += strspn( s, delim );
if ( *s )
{
const char *first = s;
s += strcspn( s, delim );
const char *last = s;
while ( last != first && ispunct( ( unsigned char )*( last - 1 ) ) )
{
--last;
}
if ( max < last - first ) max = last - first;
}
}
return max;
}
int main(void)
{
const char *s = "Why are not you using string functions?!";
printf( "The size of the longest word is %zu\n", longWordLength( s ) );
return 0;
}
The program output is
The size of the longest word is 9
Another approach is to write two functions similar to strspn and strcspn that deal with blank and punctuation symbols.
Here is a demonstrative program.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
size_t count_non_alpha( const char *s )
{
size_t n = 0;
while ( isblank( ( unsigned char )s[n] ) || ispunct( ( unsigned char )s[n] ) )
{
++n;
}
return n;
}
size_t count_alpha( const char *s )
{
size_t n = 0;
while ( s[n] && !isblank( ( unsigned char )s[n] ) && !ispunct( ( unsigned char )s[n] ) )
{
++n;
}
return n;
}
size_t longWordLength( const char *s )
{
size_t max = 0;
while ( *s )
{
s += count_non_alpha( s );
if ( *s )
{
const char *first = s;
s += count_alpha( s );
if ( max < s - first ) max = s - first;
}
}
return max;
}
int main(void)
{
const char *s = "Why are not you using string functions?!";
printf( "The size of the longest word is %zu\n", longWordLength( s ) );
return 0;
}
The program output is the same as shown above.
Please refer to my comment to your original question.
You can resolve your problem by adding the following code, after your while loop.
if (*(s - 1) != ' ' && *(s - 1) != '.' )
{
if(count>max)
{
max = count;
printf("There is a new max! It is %d\n", max);
}
}
The code checks the last character in the input string. If it is not a word terminating character, then you didn't compare the last word with the current max in the loop and hence you do it after the loop completes.
use isalpha() to check the kind of character
don't forget to count the final word if it is followed by a '\0'
#include <stdio.h>
#include <ctype.h>
unsigned longest_word(char *str)
{
unsigned length,longest;
for(longest=length = 0; ; str++) {
if (isalpha(*str)) { length++; continue; }
if (length > longest) longest = length;
length = 0;
if (!*str) break;
}
return longest;
}
int main(void)
{
char * string1 = "The longest word is short";
char * string2 = "The longest word is unbelievable";
printf("%s: %u\n", string1, longest_word( string1) );
printf("%s: %u\n", string2, longest_word( string2) );
return 0;
}

Count words from a string with multiple empty spaces

I need code that can count the words from a string without counting multiple spaces between them.
I could code a program that counts the words with only 1 empty space between them, but I don't know how I should code it when it would be more than 1 empty space. I thought something like a for loop that checks if the char before it is a space, but I don't know how to do that. And I want to mention that I'm a beginner in C.
#include <stdio.h>
#include <string.h>
int main()
{
char s[200];
int count = 0, i;
printf("enter the string: ");
fgets(s,200,stdin);
for (i = 0;s[i] != '\0';i++)
{
if (s[i] == ' ')
count++;
}
printf("number of words in given string are: %d\n", count+ 1);
return(0);
}
You can introduce a flag to tell whether the previous character was a space. Something like:
#include <stdio.h>
#include <string.h>
int main()
{
char s[200];
int count = 0, i;
int last_was_space = 1;
printf("enter the string: ");
fgets(s,200,stdin);
for (i = 0;s[i] != '\0';i++)
{
if (s[i] == ' ')
{
if (!last_was_space)
{
count++; // Only count when last char wasn't a space
last_was_space = 1;
}
}
else
{
// Update flag (unless this char is a newline)
if (s[i] != '\n') last_was_space = 0;
}
}
if (!last_was_space) ++count; // Count the last word if there wasn't a space before
printf("number of words in given string are: %d\n", count);
return(0);
}
Framing the problem in general terms helps here. Don't think of it as "counting words", or "counting spaces". Think of it as counting "transitions from separator to non-separator". Defining our terms:
Separator: start of string, or a single ASCII space
Non-separator: everything else
Examples (^ is start of string, _ is a literal space, $ is end of string):
^a_quick_brown_fox_jumps$
^ ^ ^ ^ ^ 5 transitions
^_a__quick___brownfox_jumps___$
^ ^ ^ ^ 4 transitions
^$
0 transitions
^___$
0 transitions
^__x$
^ 1 transition
Now in psuedo code:
def is_separator(char x):
return (x == NULL or x == ' ')
def is_non_separator(char x):
return (! is_separator(x))
let count = 0, last_char = NULL
while current_char = read_char():
if (is_non_separator(current_char) and is_separator(last_char)):
count++
From here, you can translate into specific languages or change the meaning of separators without affecting the logic of counting.
A bit more universal
size_t wcount(const char *s, const char *del, int countempty)
{
char *token;
size_t count = 0;
char *str = strdup(s);
if(str)
{
token = strtok(str, del);
while( token != NULL )
{
if(!strlen(token))
{
if(countempty)
{
count++;
}
}
else
{
count++;
}
token = strtok(NULL, del);
}
}
free(str);
return count;
}
int main ()
{
char str[] = "something to count ,., , . !! Stack overflow ";
printf("With empty %zu, Without empty%zu\n", wcount(str," ", 1), wcount(str," .,", 0));
}
count the words from a string without counting multiple spaces between them
Set a flag to determine if the beginning of a word is possible. Fewer special cases than looking for the end of the word.
Typically the requirement for "spaces" implies any white-space, then the task is easily coded:
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char s[200];
printf("enter the string: ");
fgets(s, sizeof s, stdin);
int count = 0;
bool beginning_of_word_possible = true;
for (const char *p = s; *p; p++) {
if (isspace((unsigned char ) *p)) {
beginning_of_word_possible = true;
} else {
if (beginning_of_word_possible) {
count++;
}
beginning_of_word_possible = false;
}
}
printf("number of words in given string are: %d\n", count);
return (0);
}
#P__J__ offered a good idea that passes in a list of delimiters. Below is a similar and short solution that does not allocate memory nor change the supplied string.
#include <string.h>
size_t word_count(const char *s, const char *delimiters) {
size_t count = 0;
while (*(s += strspn(s, delimiters))) { // Advance s by the matching delimiters.
count++;
s += strcspn(s, delimiters); // Advance s by the non-matching delimiters.
}
return count;
}
Test
int main(void) {
const char *de = " \n";
printf("%zu\n", word_count("", de));
printf("%zu\n", word_count("\n", de));
printf("%zu\n", word_count(" ", de));
printf("%zu\n", word_count("abc", de));
printf("%zu\n", word_count(" abc", de));
printf("%zu\n", word_count(" abc \n", de));
printf("%zu\n", word_count("abc xyz", de));
printf("%zu\n", word_count(" abc xyz", de));
printf("%zu\n", word_count(" abc xyz \n", de));
}
Output
0
0
0
1
1
1
2
2
2
Short and Simple Version:
#include <stdio.h>
int main(void) {
char str[] = " Hello, This is a test of a word counter";
int i = 0;
for(char* s=str; strtok(s," "); i++) s = NULL;
printf("number of words in given string are: %d\n", i);
return 0;
}
Output
Success #stdin #stdout 0s 9424KB
number of words in given string are: 9

Issue with Strings in C

Here is a program with Strings where I am trying
Pig Latin translation is simply taking the first letter of a “word” and appending that letter to the end of the word with “ay” added to the end as well
I have issue with m1=m2+3 ( resetting the Initial Marker ).
Input that I am giving : "Alex, how are you right"
The output I am expecting is : lexay, owhay reay ouyay ightray
But
I am getting this : lex,Aay way ay ayo gayi
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void initialize(char english[], char piglatin[]);
void readinput (char english[]);
int countwords(char english[]);
void convert ( int words, char english[], char piglatin[]);
void writeoutput( char piglatin[]);
int main()
{
char english[80], piglatin[80];
int words;
initialize(english, piglatin);
printf("enter the string\t");
fflush(stdin);
gets(english);
printf ("\nInput buffer contents: %s\n", english);
words = countwords(english);
convert(words,english,piglatin);
writeoutput(piglatin);
printf ("Have a nice day\n");
}
void initialize(char english[], char piglatin[])
{
int count;
for(count =0; count<80;++count)
{
english[count]=piglatin[count]=' ';
}
return;
}
/* Scan the english test and determine the number of words */
int countwords(char english[])
{
int count, words =1;
for ( count =0;count <79;++count)
{
if(english[count]==' ' && english[count+1]!=' ')
++words;
}
printf("%d\n",words);
return (words);
}
/* convert each words in to piglatin*/
void convert ( int words, char english[], char piglatin[])
{
int n, count;
int m1=0;
int m2;
/* convert each word */
for ( n=1;n<=words;++n)
{
/* locate the end of the current word*/
count = m1;
printf ("\ before conversion word contents: %d\n", count);
while ( english[count]!=' ')
{
m2=count++;
}
printf ("\ before conversion word contents: %d\n", m2);
/* transpose the first letter and add 'a', 'y'*/
for (count =m1;count<m2;++count)
{
piglatin[count+(n-1)]=english[count+1];
}
piglatin[m2+(n-1)] = english[m1];
piglatin[m2+1] = 'a';
piglatin[m2+2] = 'y';
m1=m2+3;
printf ("\ Converted word contents: %s\n", piglatin);
}
return;
}
void writeoutput( char piglatin[])
{
int count =0;
for (count =0; count <80; ++count)
{
putchar(piglatin[count]);
}
printf ("\n");
return;
}
I see various problems here:
Alex -> lex,Aay: You should check for punctuation marks when determining the end of the words, thus inserting the Aay part before the comma character
Alex -> lex,Aay: Every character from the start of a word should be converted to lowercase and the resulting first character should be converted to upper case respectively
Now the conversion function: I have changed it a bit to get you started; it should work now ( at least it does with your test string ) without taking 1 and 2 into account though
void convert(int words, char english[], char piglatin[])
{
int estart = 0;
int ppos = 0;
int m2;
for (int n = 0; n < words; n++)
{
//locate the start of the current word, to make
//sure something like this is converted:
//"Alex, how are you"
while (english[estart] == ' ')
{
//make sure we do not exceed the strings boundaries!
if (english[estart] == '\0')
{
return;
}
estart++;
}
//locate the end of the word
int eend = estart;
while (english[eend] != ' ')
{
//never forget to check for the end of the string
if (english[eend] == '\0')
{
break;
}
eend++;
}
/* transpose the first letter and add 'a', 'y'*/
for (int i = estart+1; i < eend; i++, ppos++)
{
piglatin[ppos] = english[i];
}
piglatin[ppos++] = english[estart];
piglatin[ppos++] = 'a';
piglatin[ppos++] = 'y';
//dont forget to add a whitespace or your string might behave
//very stangely!
piglatin[ppos++] = ' ';
estart = eend;
printf("\ Converted word contents: %s\n", piglatin);
}
}
I hope this gets you started in the right direction.
Please also check your array sizes for english and piglatin. The string for piglatin is alway longer than the english one but your array sizes are the same! Also i would advise you add some boundary checks to make sure you do not leave the array boundaries.

Resources