C - How to check if unwanted character is in an array? - c

I have a question about string arrays.
I am trying to find a way to check if a string has an undesired character in it.
Tested array has to only contain one of these 8 options: {'A','a','C','c','G','g','T','t'}
All the white spaces are removed prior to this checking process.
If I have two arrays
A = {AGctcgtacgtacg}
B = {CGTAagctFcg}
A should pass the test and B should fail because it has 'F' in it.
I'm thinking of using a for loop to go over each element of the array and trying to check if the character is one of the options.
const char test[] = {'A','a','C','c','G','g','T','t'};
int l = strlen(A);
char A[] = {AGctcgtacgtacg}
char B[] = {CGTAagctFcg}
for (i = 0; i < l; i++){
if (A[i] is one of the characters in test){
do nothing... (keep checking)
}
else{
break;
printf("Error: the array contains unwanted character.");
exit(1);
}
}

You can use standard C function strspn declared in header <string.h> to check whether a string contains only valid characters.
For example
#include <stdio.h>
#include <string.h>
int main( void )
{
const char *test = "AaCcGgTt";
char A[] = "AGctcgtacgtacg";
char B[] = "CGTAagctFcg";
if (A[strspn(A, test)] == '\0')
{
puts("Array A has valid characters");
}
else
{
puts("Array A has invalid characters");
}
if (B[strspn(B, test)] == '\0')
{
puts("Array B has valid characters");
}
else
{
puts("Array B has invalid characters");
}
}
The program output is
Array A has valid characters
Array B has invalid characters
If you need to know also the position of the first invalid character then you can write for example
#include <stdio.h>
#include <string.h>
int main()
{
const char *test = "AaCcGgTt";
char A[] = "AGctcgtacgtacg";
char B[] = "CGTAagctFcg";
size_t n;
if (A[n = strspn(A, test)] == '\0')
{
puts("Array A has valid characters");
}
else
{
puts("Array A has invalid characters");
printf("Invalid character is %c at position %zu\n", A[n], n);
}
if (B[n = strspn(B, test)] == '\0')
{
puts("Array B has valid characters");
}
else
{
puts("Array B has invalid characters");
printf("Invalid character is %c at position %zu\n", B[n], n);
}
}
The program output is
Array A has valid characters
Array B has invalid characters
Invalid character is F at position 8

Try using strchr(...) NOTE that test needs to be NUL terminated
const char test[] = {'A','a','C','c','G','g','T','t','\0'};
int l = strlen(A);
char A[] = {AGctcgtacgtacg}
char B[] = {CGTAagctFcg}
for (i = 0; i < l; i++){
if (strchr(test, A[i])){
do nothing... (keep checking)
}
else{
break;
printf("Error: the array contains unwanted character.");
exit(1);
}
}

Related

I am writing a code about replacing a word in a string with another word and removing repeats. Cannot finish it but got half to work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//This function converts a string to a sentence.
void
StrtoSent(char *string)
{
int length = 0,n = 0;
length = strlen(string);
for(n = 0; n < length; n++){
if((n ==0) && (string[n] >= 'b' && string[n] <= 'y')){
string[n] = string[n] - 32;
}
else if(string[n] == '.'){
if(string[n + 1] == ' '){
if(string[n+2]>= 'b' && string[n+2]<= 'y'){
string[n+2]= string[n+1] - 32;
}
}
}
}
}
int
main(void)
{
char string[50] = {0};
int length = 0,n = 0,a = 0,d = 0;
printf("\n\nEnter a wordstring Neo: ");
gets(string);
StrtoSent(string);//Here,we send the string off to the function
char str[] = "The xitraM is acutally the Matrix!";
char j[] = "xitraM";
char e[] = "Matrix";
char *result = NULL;
printf("Original string: %s\n",str);
printf("The converted sentence: %s",string);
char input[200];
getchar();
fflush(stdin);
fgets(input,200,stdin);
char c;
if (isdigit(c)) {
int n = c - '0'; //'0'-'9' -> 0 - 9
printf("%c is coverted to %d\n",c,n);
}
while((c=getchar()) != EOF) {
if(islower(c))
printf("%c will be converted to %c\n",c,toupper(c));
if(isupper(c))
printf("%c in lowercase is %c\n",c,tolower(c));
getchar();
}
}
How do I replace the word xitraM and get it to be like this output:
The xirtaM is actually the MATRIX!
Converted sentence:
The Matrix is actually the MATRIX!
Original:
a blACk cAT is in the xirtaM.
Converted sentence:
A Black Cat is in the Matrix.
My code allows you
so far to enter a wordstring and it will return a string, and it will
fix the //code if there are capitals in the wrong place and if the
punctuation is wrong, but I cannot seem to get the code to replace
xitraM with Matrix and I am stuck on that.
Some help would be great -- thanks!
This is prefaced by my top comments.
There are many issues with the code.
Never use gets--the man page for it says to not use it [and why].
Your main is reading a line but not doing much with it.
The loop at the bottom doing getchar makes no sense because you've already read the line with the fgets above. It looks like you're trying to preview the capitalization.
For the word substitution, use two buffers. An input and a separate output buffer. Although xirtaM and Matrix are the same length, using separate buffers allows the length of the strings to differ (i.e. it's more general).
You can loop through the input using strstr to find the "bad" string. Then, copy over the partial string that precedes it. Skip the bad string in the input. Then, copy over the "good" string to the output.
Your capitalization function makes no sense [and appears to do nothing].
Also, converting the "black cat" string, from your example isn't general because it would need to special case "cat" to produce "Cat". For English, "cat" is not a proper name, so it should be all lowercase.
Unfortunately, your code needed some heavy refactoring in order to work.
I had to change the capitalization function to just capitalize the first char of the first word of each sentence as that was the only thing that made sense to me [adjust to suit your needs].
I wired in your two test cases. And, I've added some debug printf statements.
Anyway, here's the code. I've annotated it, so that the part you had an issue with [the word substitution] should give you some ideas.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//This function converts a string to a sentence.
void
StrtoSent(char *string)
{
int length = 0,n = 0;
length = strlen(string);
for(n = 0; n < length; n++){
if((n ==0) && (string[n] >= 'b' && string[n] <= 'y')){
string[n] = string[n] - 32;
}
else if(string[n] == '.'){
if(string[n + 1] == ' '){
if(string[n+2]>= 'b' && string[n+2]<= 'y'){
string[n+2]= string[n+1] - 32;
}
}
}
}
}
// fixcap -- capitalize sentences in the string
void
fixcap(char *string)
{
int capflg = 1;
while (1) {
int chr = *string;
// end of string
if (chr == 0)
break;
switch (chr) {
case ' ':
break;
case '.': // end of sentence -- restart capitalization
case '!':
capflg = 1;
break;
default:
// capitalize the [first letter of the] first word of a sentence
if (capflg) {
chr = toupper((unsigned char) chr);
capflg = 0;
}
else
chr = tolower((unsigned char) chr);
break;
}
*string++ = chr;
}
}
// fixword -- substitute word in string
void
fixword(char *out,const char *inp,const char *bad,const char *good)
{
int lenbad = strlen(bad);
int lengood = strlen(good);
char *cp;
int lencpy;
while (1) {
// find the "bad" string in the input
cp = strcasestr(inp,bad);
// the remaining input string is good -- copy it
if (cp == NULL) {
strcpy(out,inp);
break;
}
// get the length of the string leading up to the "bad" string
// copy it over and advance the pointers
lencpy = cp - inp;
memcpy(out,inp,lencpy);
inp += lencpy;
out += lencpy;
// skip over the bad string in the input
inp += lenbad;
// copy over the "good" string and advance the output pointer
strcpy(out,good);
out += lengood;
}
}
// fixall -- perform all actions
void
fixall(const char *string)
{
char inp[1000];
char out[1000];
strcpy(inp,string);
printf("DEBUG: BEFORE '%s'\n",inp);
//Here,we send the string off to the function
#if 0
StrtoSent(inp);
printf("DEBUG: AFTCAP '%s'\n",inp);
#endif
#if 1
fixcap(inp);
printf("DEBUG: AFTCAP '%s'\n",inp);
#endif
fixword(out,inp,"xirtaM","Matrix");
printf("DEBUG: AFTFIX '%s'\n",out);
}
// doline -- read and process an input line
int
doline(void)
{
char *cp;
char string[1000];
int more;
do {
printf("\n\nEnter a wordstring Neo: ");
cp = fgets(string,sizeof(string),stdin);
more = (cp != NULL);
if (! more)
break;
// strip newline
cp = strchr(string,'\n');
if (cp != NULL)
*cp = 0;
fixall(string);
} while (0);
return more;
}
int
main(void)
{
#if 0
char string[50] = {0};
int length = 0,n = 0,a = 0,d = 0;
#endif
// default test cases
fixall("The xirtaM is acutally the Matrix!");
fixall("a blACk cAT is in the xirtaM.");
// read input lines and do conversions
while (1) {
if (! doline())
break;
}
#if 0
char str[] = "The xirtaM is acutally the Matrix!";
char j[] = "xirtaM";
char e[] = "Matrix";
char *result = NULL;
printf("Original string: %s\n",str);
printf("The converted sentence: %s",string);
char input[200];
getchar();
fflush(stdin);
fgets(input,200,stdin);
char c;
if (isdigit(c)) {
int n = c - '0'; //'0'-'9' -> 0 - 9
printf("%c is coverted to %d\n",c,n);
}
while((c=getchar()) != EOF) {
if(islower(c))
printf("%c will be converted to %c\n",c,toupper(c));
if(isupper(c))
printf("%c in lowercase is %c\n",c,tolower(c));
getchar();
}
#endif
return 0;
}
Here is the program output for the default test cases:
DEBUG: BEFORE 'The xirtaM is acutally the Matrix!'
DEBUG: AFTCAP 'The xirtam is acutally the matrix!'
DEBUG: AFTFIX 'The Matrix is acutally the matrix!'
DEBUG: BEFORE 'a blACk cAT is in the xirtaM.'
DEBUG: AFTCAP 'A black cat is in the xirtam.'
DEBUG: AFTFIX 'A black cat is in the Matrix.'

A program that prints even and odd characters from a string

This is for Homework
I have to write a program that asks the user to enter a string, then my program would separate the even and odd values from the entered string. Here is my program.
#include <stdio.h>
#include <string.h>
int main(void) {
char *str[41];
char odd[21];
char even[21];
int i = 0;
int j = 0;
int k = 0;
printf("Enter a string (40 characters maximum): ");
scanf("%s", &str);
while (&str[i] < 41) {
if (i % 2 == 0) {
odd[j++] = *str[i];
} else {
even[k++] = *str[i];
}
i++;
}
printf("The even string is:%s\n ", even);
printf("The odd string is:%s\n ", odd);
return 0;
}
When I try and compile my program I get two warnings:
For my scanf I get "format '%s' expects arguments of type char but argument has 'char * (*)[41]". I'm not sure what this means but I assume it's because of the array initialization.
On the while loop it gives me the warning that says comparison between pointer and integer. I'm not sure what that means either and I thought it was legal in C to make that comparison.
When I compile the program, I get random characters for both the even and odd string.
Any help would be appreciated!
this declaration is wrong:
char *str[41];
you're declaring 41 uninitialized strings. You want:
char str[41];
then, scanf("%40s" , str);, no & and limit the input size (safety)
then the loop (where your while (str[i]<41) is wrong, it probably ends at once since letters start at 65 (ascii code for "A"). You wanted to test i against 41 but test str[i] against \0 instead, else you get all the garbage after nul-termination char in one of odd or even strings if the string is not exactly 40 bytes long)
while (str[i]) {
if (i % 2 == 0) {
odd[j++] = str[i];
} else {
even[k++] = str[i];
}
i++;
}
if you want to use a pointer (assignement requirement), just define str as before:
char str[41];
scan the input value on it as indicated above, then point on it:
char *p = str;
And now that you defined a pointer on a buffer, if you're required to use deference instead of index access you can do:
while (*p) { // test end of string termination
if (i % 2 == 0) { // if ((p-str) % 2 == 0) { would allow to get rid of i
odd[j++] = *p;
} else {
even[k++] = *p;
}
p++;
i++;
}
(we have to increase i for the even/odd test, or we would have to test p-str evenness)
aaaand last classical mistake (thanks to last-minute comments), even & odd aren't null terminated so the risk of getting garbage at the end when printing them, you need:
even[k] = odd[j] = '\0';
(as another answer states, check the concept of even & odd, the expected result may be the other way round)
There are multiple problems in your code:
You define an array of pointers char *str[41], not an array of char.
You should pass the array to scanf instead of its address: When passed to a function, an array decays into a pointer to its first element.
You should limit the number of characters read by scanf.
You should iterate until the end of the string, not on all elements of the array, especially with (&str[i] < 41) that compares the address of the ith element with the value 41, which is meaningless. The end of the string is the null terminator which can be tested with (str[i] != '\0').
You should read the characters from str with str[i].
You should null terminate the even and odd arrays.
Here is a modified version:
#include <stdio.h>
int main(void) {
char str[41];
char odd[21];
char even[21];
int i = 0;
int j = 0;
int k = 0;
printf("Enter a string (40 characters maximum): ");
if (scanf("%40s", str) != 1)
return 1;
while (str[i] != '\0') {
if (i % 2 == 0) {
odd[j++] = str[i];
} else {
even[k++] = str[i];
}
i++;
}
odd[j] = even[k] = '\0';
printf("The even string is: %s\n", even);
printf("The odd string is: %s\n", odd);
return 0;
}
Note that your interpretation of even and odd characters assumes 1-based offsets, ie: the first character is an odd character. This is not consistent with the C approach where an even characters would be interpreted as having en even offset from the beginning of the string, starting at 0.
Many answers all ready point out the original code`s problems.
Below are some ideas to reduce memory usage as the 2 arrays odd[], even[] are not needed.
As the "even" characters are seen, print them out.
As the "odd" characters are seen, move them to the first part of the array.
Alternative print: If code used "%.*s", the array does not need a null character termination.
#include <stdio.h>
#include <string.h>
int main(void) {
char str[41];
printf("Enter a string (40 characters maximum): ");
fflush(stdout);
if (scanf("%40s", str) == 1) {
int i;
printf("The even string is:");
for (i = 0; str[i]; i++) {
if (i % 2 == 0) {
str[i / 2] = str[i]; // copy character to an earlier part of `str[]`
} else {
putchar(str[i]);
}
}
printf("\n");
printf("The odd string is:%.*s\n ", (i + 1) / 2, str);
}
return 0;
}
or simply
printf("The even string is:");
for (int i = 0; str[i]; i++) {
if (i % 2 != 0) {
putchar(str[i]);
}
}
printf("\n");
printf("The odd string is:");
for (int i = 0; str[i]; i++) {
if (i % 2 == 0) {
putchar(str[i]);
}
}
printf("\n");
here is your solution :)
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[41];
char odd[21];
char even[21];
int i = 0;
int j = 0;
int k = 0;
printf("Enter a string (40 characters maximum): ");
scanf("%s" , str);
while (i < strlen(str))
{
if (i % 2 == 0) {
odd[j++] = str[i];
} else {
even[k++] = str[i];
}
i++;
}
odd[j] = '\0';
even[k] = '\0';
printf("The even string is:%s\n " , even);
printf("The odd string is:%s\n " , odd);
return 0;
}
solved the mistake in the declaration, the scanning string value, condition of the while loop and assignment of element of array. :)

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.

strings to arrays then print in c

I am trying to take a user inputted string and look at each code to see if it appears in another string of strings. So far my code works.
If the word is successfully found then the alpha representation is to be added to an array that will eventually be printed, but only if all codes were found.
I am having issues with what gets stored in my array that is going to be printed.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char *string;
typedef char *alpha;
int main(void)
{
string morse[4]={".-", "-...","----.", ".."};
string alpha[4]={"A", "B", "9", "I"};
char prntArr[50];
char *input;
char *hold;
input = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
int ret;
int x;
int w=0;
int z=0;
printf("please enter a string\n");
scanf("%[^\n]",input);
do{
if (input[i] !=' ')
{
hold[j] = input[i];
j++;
}
else
{
hold[j]='\0';
for (x=0;x<4;x++)
{
printf("value of x %d\n",x);
ret = strcmp(morse[x], hold);
if (ret==0)
{
printf("%s\n",alpha[x]);
prntArr[w]=*hold;
w++;
x=4;
}
else
{
ret=1;
printf("invalid Morse code!");
}
}
j = 0;
}
i++;
}while(input[i] !='\0');
for (z=0;z<50;z++)
{
printf("%c",prntArr[z]);
}
return 0;
free(input);
}
The problem you asked about is caused by the way prntArr is used in the program. It really should be an array of character pointers into the alpha array. Instead, it's manipulated as an array of characters into which the first character of each morse code element is stored. And when it's printed, the variable that tracks how much of the array is used is simply ignored.
Another problem is that your code uses spaces to break the codes but there won't necessarily be a space at the end of the line so a code might get missed. In the program below, I switched out scanf() for fgets() which leaves a newline character on the end of the input which we can use, like space, to indicate the end of a code.
Other problems: you print the invalid Morse code message at the wrong point in the code and you print it to stdout instead of stderr; you remember to free input but forget to free hold; you put code after return that never gets called.
Below is a rework of your code that addresses the above problems along with some style issues:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(void)
{
char *morse[] = {".-", "-...", "----.", ".."};
char *alpha[] = {"A" , "B" , "9" , "I" };
char *print_array[50];
int print_array_index = 0;
char hold[50];
int hold_index = 0;
char input[200];
int i = 0;
printf("please enter a string: ");
fgets(input, sizeof(input), stdin);
while (input[i] !='\0') {
if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';
bool found = false;
for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "invalid Morse code: %s\n", hold);
}
hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}
i++;
}
for (int x = 0; x < print_array_index; x++)
{
printf("%s ", print_array[x]);
}
printf("\n");
return 0;
}
SAMPLE RUNS
> ./a.out
please enter a string: ----. -... .- ..
9 B A I
>
> ./a.out
please enter a string: .- --- ..
invalid Morse code: ---
A I
>

C program, Reversing an array

I am writing C program that reads input from the standard input a line of characters.Then output the line of characters in reverse order.
it doesn't print reversed array, instead it prints the regular array.
Can anyone help me?
What am I doing wrong?
main()
{
int count;
int MAX_SIZE = 20;
char c;
char arr[MAX_SIZE];
char revArr[MAX_SIZE];
while(c != EOF)
{
count = 0;
c = getchar();
arr[count++] = c;
getReverse(revArr, arr);
printf("%s", revArr);
if (c == '\n')
{
printf("\n");
count = 0;
}
}
}
void getReverse(char dest[], char src[])
{
int i, j, n = sizeof(src);
for (i = n - 1, j = 0; i >= 0; i--)
{
j = 0;
dest[j] = src[i];
j++;
}
}
You have quite a few problems in there. The first is that there is no prototype in scope for getReverse() when you use it in main(). You should either provide a prototype or just move getReverse() to above main() so that main() knows about it.
The second is the fact that you're trying to reverse the string after every character being entered, and that your input method is not quite right (it checks an indeterminate c before ever getting a character). It would be better as something like this:
count = 0;
c = getchar();
while (c != EOF) {
arr[count++] = c;
c = getchar();
}
arr[count] = '\0';
That will get you a proper C string albeit one with a newline on the end, and even possibly a multi-line string, which doesn't match your specs ("reads input from the standard input a line of characters"). If you want a newline or file-end to terminate input, you can use this instead:
count = 0;
c = getchar();
while ((c != '\n') && (c != EOF)) {
arr[count++] = c;
c = getchar();
}
arr[count] = '\0';
And, on top of that, c should actually be an int, not a char, because it has to be able to store every possible character plus the EOF marker.
Your getReverse() function also has problems, mainly due to the fact it's not putting an end-string marker at the end of the array but also because it uses the wrong size (sizeof rather than strlen) and because it appears to re-initialise j every time through the loop. In any case, it can be greatly simplified:
void getReverse (char *dest, char *src) {
int i = strlen(src) - 1, j = 0;
while (i >= 0) {
dest[j] = src[i];
j++;
i--;
}
dest[j] = '\0';
}
or, once you're a proficient coder:
void getReverse (char *dest, char *src) {
int i = strlen(src) - 1, j = 0;
while (i >= 0)
dest[j++] = src[i--];
dest[j] = '\0';
}
If you need a main program which gives you reversed characters for each line, you can do that with something like this:
int main (void) {
int count;
int MAX_SIZE = 20;
int c;
char arr[MAX_SIZE];
char revArr[MAX_SIZE];
c = getchar();
count = 0;
while(c != EOF) {
if (c != '\n') {
arr[count++] = c;
c = getchar();
continue;
}
arr[count] = '\0';
getReverse(revArr, arr);
printf("'%s' => '%s'\n", arr, revArr);
count = 0;
c = getchar();
}
return 0;
}
which, on a sample run, shows:
pax> ./testprog
hello
'hello' => 'olleh'
goodbye
'goodbye' => 'eybdoog'
a man a plan a canal panama
'a man a plan a canal panama' => 'amanap lanac a nalp a nam a'
Your 'count' variable goes to 0 every time the while loop runs.
Count is initialised to 0 everytime the loop is entered
you are sending the array with each character for reversal which is not a very bright thing to do but won't create problems. Rather, first store all the characters in the array and send it once to the getreverse function after the array is complete.
sizeof(src) will not give the number of characters. How about you send i after the loop was terminated in main as a parameter too. Ofcourse there are many ways and various function but since it seems like you are in the initial stages, you can try up strlen and other such functions.
you have initialised j to 0 in the for loop but again, specifying it INSIDE the loop will initialise the value everytime its run from the top hence j ends up not incrmenting. So remore the j=0 and i=0 from INSIDE the loop since you only need to get it initialised once.
check this out
#include <stdio.h>
#include <ctype.h>
void getReverse(char dest[], char src[], int count);
int main()
{
// *always* initialize variables
int count = 0;
const int MaxLen = 20; // max length string, leave upper case names for MACROS
const int MaxSize = MaxLen + 1; // add one for ending \0
int c = '\0';
char arr[MaxSize] = {0};
char revArr[MaxSize] = {0};
// first collect characters to be reversed
// note that input is buffered so user could enter more than MAX_SIZE
do
{
c = fgetc(stdin);
if ( c != EOF && (isalpha(c) || isdigit(c))) // only consider "proper" characters
{
arr[count++] = (char)c;
}
}
while(c != EOF && c != '\n' && count < MaxLen); // EOF or Newline or MaxLen
getReverse( revArr, arr, count );
printf("%s\n", revArr);
return 0;
}
void getReverse(char dest[], char src[], int count)
{
int i = count - 1;
int j = 0;
while ( i > -1 )
{
dest[j++] = src[i--];
}
}
Dealing with strings is a rich source of bugs in C, because even simple operations like copying and modifying require thinking about issues of allocation and storage. This problem though can be simplified considerably by thinking of the input and output not as strings but as streams of characters, and relying on recursion and local storage to handle all allocation.
The following is a complete program that will read one line of standard input and print its reverse to standard output, with the length of the input limited only by the growth of the stack:
int florb (int c) { return c == '\n' ? c : putchar(florb(getchar())), c; }
main() { florb('-'); }
..or check this
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
char *my_rev(const char *source);
int main(void)
{
char *stringA;
stringA = malloc(MAX); /* memory allocation for 100 characters */
if(stringA == NULL) /* if malloc returns NULL error msg is printed and program exits */
{
fprintf(stdout, "Out of memory error\n");
exit(1);
}
else
{
fprintf(stdout, "Type a string:\n");
fgets(stringA, MAX, stdin);
my_rev(stringA);
}
return 0;
}
char *my_rev(const char *source) /* const makes sure that function does not modify the value pointed to by source pointer */
{
int len = 0; /* first function calculates the length of the string */
while(*source != '\n') /* fgets preserves terminating newline, that's why \n is used instead of \0 */
{
len++;
*source++;
}
len--; /* length calculation includes newline, so length is subtracted by one */
*source--; /* pointer moved to point to last character instead of \n */
int b;
for(b = len; b >= 0; b--) /* for loop prints string in reverse order */
{
fprintf(stdout, "%c", *source);
len--;
*source--;
}
return;
}
Output looks like this:
Type a string:
writing about C programming
gnimmargorp C tuoba gnitirw

Resources