scanf() and for loop not cooperating - c

I'm writing a function called GetPattern() that will be used in my main() function.
Here's the context of how my main() uses the GetPattern() function.
int main(void)
{
int attempt=0, option=-1;
char pattern[SIZE+1], replacement[SIZE+1];
char name[20];
FILE *in, *out;
printf("Enter the pattern to find:");
GetPattern(pattern);
out = CreateFile();
Find(in, pattern, out);
fclose(in);
fclose(out);
return 0;
}
And here's my GetPattern() function:
void GetPattern(char *tmp)
{
// prompt the user for the pattern to be found/replaced
// note: any character, including ' ', maybe be part of the pattern
// we assume that the pattern has no more than 20 characters. If the user
// enters more than 20 characters, only the first 20 will be used.
int i;
for (i = 0; i < 20; i++) // iterate 20 times
{
scanf(" %c", &tmp[i]);
if (tmp[i] == '\n') // if user hits enter, break the loop
{
tmp[i] = '\0'; // insert '\0' at the end of the array
break;
}
else
tmp[i+1] = '\0'; // insert '\0' at the end of the array
}
printf("%s\n", tmp); // see what's in tmp[]
return;
}
The GetPattern() function works by itself; separate from the main() function, but when I put it into main, it exclusively accepts 20 characters and no less. Even when I hit ENTER (i.e., '\n'), the loop doesn't break--it keeps going.
Do you see anything obviously wrong with this code?

I think using getc() will help you.
for (i = 0; i < 20; i++) // iterate 20 times
{
//scanf(" %c", &tmp[i]);
tmp[i]=getc(stdin);/////
if (tmp[i] == '\n') // if user hits enter, break the loop
{
tmp[i] = '\0'; // insert '\0' at the end of the array
break;
}
else
tmp[i+1] = '\0'; // insert '\0' at the end of the array
}

Related

print each word in separate lines

My program aims to print each word in the sentence on a separate line.but I should print it with %s not %c! I already try to implement it but the program does not give me a correct output ! my idea is when you find null character
1- print the word
2- return the index of the temp array to 0 and store a new word
int main () {
char sen[100];
char cpy [100];
printf("Entter a sentence ");
gets(sen);
int len = strlen(sen);
int i = 0;
int k =0;
for (i=0 ; i<len;i++)
{
if (sen[i]!='\0')
{
cpy[k++]+=sen[i];
}
else{
printf("%s\n",cpy);
k=0;}
}
}
You confound null character and space character. Null character \0 stands for "end of string" : the strlen function returns the number of characters before the first \0.
In your forloop, you want to display each word separated by so you have to test with the caracter instead of \0.
Also to correctly display your string you have to end the string with the \0 character. So before the instruction printf you must do cpy[k] = '\0';.
if (sen[i]!='\0') will always be true as pointed by Julien Vernay, you need if (sen[i]!= ' ') instead of if (sen[i]!='\0'), as there are spaces between words, to seprate them.
Also in cpy[k++]+=sen[i]; you are adding sen[i] to cpy[k++] which seams weird, I think what you need is cpy[k++] = sen[i];
Modify your loop as follows...
for (i=0 ; i<len; i++) {
int flag = 0;
while(sen[i] == ' ') i++; // multiple spaces
while(sen[i] != ' ' && sen[i] != '\0') {
cpy[k++] = sen[i];
flag = 1;
i++;
}
if(flag) {
cpy[k] = '\0';
printf("%s\n",cpy);
k=0;
}
}
You can have to not bother with doing a copy - all you need to do is essentially replace spaces with new lines. So here is the code to do this:
#include <stdio.h>
int main()
{
char sen[100];
bool last_char_space = true;
printf("Please enter a sentence: ");
fflush(stdout);
fgets(sen, 100, stdin);;
for (int loop = 0; sen[loop]; ++loop) { // send[loop] is true until end of string - saves repeatedly calling strlen
if (send[loop] == ' ') { // A space
if (last_char_space) { // Last character not a space, put new line
fputc('\n', stdout);
}
last_char_space = true; // Record the fact that we are between words
} else {
fputc(sen[loop], stdout); // Not a space - print it
last_char_space = false; // We are working on a word
}
}
return 0;
}

C Program to Get Characters into Array and Reverse Order

I'm trying to create a C program that accepts a line of characters from the console, stores them in an array, reverses the order in the array, and displays the reversed string. I'm not allowed to use any library functions other than getchar() and printf(). My attempt is below. When I run the program and enter some text and press Enter, nothing happens. Can someone point out the fault?
#include <stdio.h>
#define MAX_SIZE 100
main()
{
char c; // the current character
char my_strg[MAX_SIZE]; // character array
int i; // the current index of the character array
// Initialize my_strg to null zeros
for (i = 0; i < MAX_SIZE; i++)
{
my_strg[i] = '\0';
}
/* Place the characters of the input line into the array */
i = 0;
printf("\nEnter some text followed by Enter: ");
while ( ((c = getchar()) != '\n') && (i < MAX_SIZE) )
{
my_strg[i] = c;
i++;
}
/* Detect the end of the string */
int end_of_string = 0;
i = 0;
while (my_strg[i] != '\0')
{
end_of_string++;
}
/* Reverse the string */
int temp;
int start = 0;
int end = (end_of_string - 1);
while (start < end)
{
temp = my_strg[start];
my_strg[start] = my_strg[end];
my_strg[end] = temp;
start++;
end--;
}
printf("%s\n", my_strg);
}
It seems like in this while loop:
while (my_strg[i] != '\0')
{
end_of_string++;
}
you should increment i, otherwise if my_strg[0] is not equal to '\0', that's an infinite loop.
I'd suggest putting a breakpoint and look what your code is doing.
I think you should look at your second while loop and ask yourself where my_string[i] is being incremented because to me it looks like it is always at zero...

A program to remove common alphabets from character array

void main()
{
int i, j, k,flag=1;
char key[10], keyword[10];
gets(key);
i=0;
j=0;
while(key[i]!='\0') {
k=0;
while(keyword[k]!='\0') {
if(key[i]==keyword[k]) {
i++;
flag=0;
break;
}
k++;
}
if(flag==1) {
keyword[j]=key[i];
j++;
i++;
}
flag=1;
}
}
Here I tried to copy unique alphabets from array to another array ..means duplicate alphabet should not copied in another array..it shows right output but along with that it shows some garbage values like smiley or something till the length of original input array(i.e.key[])
You need to add a terminator to the unique character string both at the time it is initialized, and every time a new letter is added:
#include <stdio.h>
int main() {
int i = 0, j = 0;
char redundant[10], unique[10] = { '\0' };
gets(redundant);
while (redundant[i] != '\0') {
int k = 0, flag = 1;
while (unique[k] != '\0') {
if (redundant[i] == unique[k]) {
flag = 0;
break;
}
k++;
}
if (flag) {
unique[j++] = redundant[i];
unique[j] = '\0';
}
i++;
}
printf("%s -> %s\n", redundant, unique);
return(0);
}
OUTPUT
% ./a.out
warning: this program uses gets(), which is unsafe.
aardvark
aardvark -> ardvk
%
Now let's consider a different approach that wastes some space to simplify and speed up the code:
#include <stdio.h>
#include <string.h>
int main() {
unsigned char seen[1 << (sizeof(char) * 8)] = { 0 }; // a flag for every ASCII character
char redundant[32], unique[32];
(void) fgets(redundant, sizeof(redundant), stdin); // gets() is unsafe
redundant[strlen(redundant) - 1] = '\0'; // toss trailing newline due to fgets()
int k = 0; // unique character counter
for (int i = 0; redundant[i] != '\0'; i++) {
if (!seen[(size_t) redundant[i]]) {
unique[k++] = redundant[i];
seen[(size_t) redundant[i]] = 1; // mark this character as seen
}
}
unique[k] = '\0'; // terminate the new unique string properly
printf("%s -> %s\n", redundant, unique);
return 0;
}
Instead of a second, inner loop to search if a letter has been copied already, we use an array of flags (boolean), where the letter is the index, to determine if the letter has been processed.
Another thing you might want to think about is whether to treat upper and lower case differently or fold them into one.

Program that checks if an array is a palindrome

I'm trying to create a program that checks if a given array/string is a palindrome or not and its not working. The program just prints "0" on every given array, even on palindromes.
int main()
{
char string[100]= {0};
char stringReverse[100]= {0};
int temp = 0;
int firstLetter = 0;
int lastLetter = 0;
printf("Please enter a word or a sentence: ");
fgets(string, 100, stdin);
strcpy(stringReverse , string); // This function copies the scanned array to a new array called "stringReverse"
firstLetter = 0;
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
// This while reverses the array and insert it to a new array called "stringReverse"
while(firstLetter < lastLetter)
{
temp = stringReverse[firstLetter];
stringReverse[firstLetter] = stringReverse[lastLetter];
stringReverse[lastLetter] = temp;
firstLetter++;
lastLetter--;
}
printf("%s %s", stringReverse, string);
if ( strcmp(stringReverse , string) == 0)
{
printf("1");
}
else
{
printf("0");
}
}
Lets say we implement a simple fun to do that
int check_palindrome (const char *s) {
int i,j;
for (i=0,j=strlen(s)-1 ; i<j ; ++i, --j) {
if (s[i] != s[j]) return 0; // Not palindrome
}
return 1; //Palindrome
}
I think this is far more simpler ;)
For the code posted in question:
Be aware of fgets(). It stops in the first '\n' or EOF and keeps the '\n' character.
So if you give radar for ex, the result string will be "radar\n", which doesn't match with "\nradar"
The Problem:
Let's say you enter the string RACECAR as input for your program and press enter, this puts a newline character or a '\n' in your buffer stream and this is also read as part of your string by fgets, and so your program effectively ends up checking if RACECAR\n is a palindrome, which it is not.
The Solution:
After you initialize lastLetter to strlen(string) - 1 check if the last character in your string (or the character at the lastLetter index is the newline character (\n) and if so, decrease lastLetter by one so that your program checks if the rest of your string (RACECAR) is a palindrome.
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
// Add these 2 lines to your code
// Checks if the last character of the string read by fgets is newline
if (string[lastLetter] == '\n')
lastLetter--;
fgets adds a '\n' at the end.
So if the user entered "aba", string contains "aba\n".
reverseString contains "\naba".
So it doesn't match.
After the fgets, add this code
int l = strlen(string) - 1;
string[l] = 0;
This will strip out the '\n' at the end before copying it to reverseString.
That aside, you can do this whole program inplace without the need of a second buffer or strcpy or strlen calls.
You have several issues in your code:
first you forgot the last closing brace };
then you forgot to remove the trailing \n (or maybe also \r under Windows) in string;
you don't need to revert the string into a new string; a one-pass check is enough:
Here is a working code:
#include <stdio.h>
#include <string.h>
int main()
{
char string[100]= {0};
int temp = 0;
int firstLetter = 0;
int lastLetter = 0;
printf("Please enter a word or a sentence: ");
fgets(string, 100, stdin);
firstLetter = 0;
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
while ((string[lastLetter]=='\n')||(string[lastLetter]=='\r')) {
lastLetter--;
}
// This while reverses the array and insert it to a new array called "stringReverse"
temp = 1;
while(firstLetter < lastLetter)
{
if (string[firstLetter] != string[lastLetter]) {
temp = 0;
break;
}
firstLetter++;
lastLetter--;
}
if ( temp )
{
printf("1");
}
else
{
printf("0");
}
}
You can do it by this simpleway also.
#include <stdio.h>
#include <string.h>
int main()
{
char string[10], revString[10];
printf("Enter string for reversing it...\n");
scanf("%s", string);
int stringLength = strlen(string);
for(int i = 0; string[i] != '\0'; i++, stringLength--)
{
revString[i] = string[stringLength - 1];
}
if(strcmp(string, revString) == 0)
printf("Given string is pelindrom\n");
else
printf("Given string is not pelindrom\n");
}
#include<stdio.h>
#include<string.h>`enter code here`
void fun(char *a);
int main ()
{
char p[100];
char *s=p;
printf("enter the string");
scanf("%[^\n]",s);
fun(s);
}
void fun(char *a)
{
if(*a && *a!='\n')
{
fun(a+1);
putchar(*a);
}
}
// use this approach better time complexity and easier work hope this helps

How can I replace getchar();?

#include <stdio.h>
int main (void)
{
int n;
printf("Give the number of words you want to input.");
scanf("%d",&n);
int letters[n],i,j,count,key,k;
char str[100];
//Scans each word, counts it's letters and stores it in the next available
//position in "letters" array.
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
str[j] = getchar();
j++;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
//Compacts the data by figuring out which cells have the same number of letters
for (i=0;i<n;i++)
{
key = letters[i];
count = 0;
for (j=i+1;j<=n;j++)
{
if (key==letters[j])
{
count += 1;
letters[j] = 0;
}
}
letters[i] = count;
}
//creates a histogram
i=0;
do{
printf("%d|",i);
for (j=1;j<=letters[i];j++)
{
printf("*");
}
printf("\n");
i++;
}while ((i<=n));
return 0;
}
I understand that getchar(); reads, the first enter (\n) , user hits, to give the amount of words he wants to input, and thus expects one less word.
Also, I get an infite loop for some reason at the end. Any help and ideas would be appreciated. Thanks in advance.
Change the first block of your code to look like this:
(test the output of getchar, and continues only if not EOF)
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
a = getchar();
if(a >= 0)
{
str[j] = a;
j++;
}
else break;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
But regarding your question: How can I replace getchar();? Have you considered using scanf()?
EDIT
Here is a simple example of using scanf() and printf() to prompt for input and then display input. It will allow user to input entire words or sentences (up to 80 characters) until 'q' is entered. Not exactly what you are doing, but you should be able to adapt it to your code... (run this)
int main(void)
{
char buf[80]={""};
while( strcmp(buf, "q") != 0) //enter a 'q' to quit
{
buf[0]=0;
printf("enter string:\n");
scanf("%s", buf);
printf("%s\n", buf);
}
}
Wouldn't it be easier to update the letter count in the first loop?
memset(letters, 0, n);
for (i=0;i<n;i++)
{
char* s = str;
int j=0;
printf("Give the next word.");
do{
*s = getchar();
++j;
}while (*(s++)!='\n');
s[-1] = '\0';
letters[j-1]++;
}
As a result the second loop will be unnecessary.
The following two lines have the wrong end condition; should be <n, not <=n. Currently they retrieve an uninitialized array element. Since you declared str as a local variable, that element is typically populated with garbage, i.e. a very big random number. That might explain why it takes extreme long (but possibly not forever) for the last loop to finish.
for (j=i+1;j<=n;j++)
}while ((i<=n));
Also, I assume line n of the histogram should contain the number of words that have n letters? That's not what you're doing right now.
letters[i] = count;
That line should have been:
letters[key] = count;
But to make that work, you should not overwrite the same array letters; you must declare a new array for your histogram, otherwise the second loop will destroy its own input.
By the way, str seems totally redundant. Is it there for debugging purposes?

Resources