In this program, when I enter 8 characters, it screws up the whole program, and I think it has something to do with clearing the input buffer when you enter more than or equal to SIZE characters, how do I make it so that it clears any overflow of characters a user may enter?
Thanks for any help!
#include <stdio.h>
#define SIZE 8
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
char array[SIZE],search;
int found[SIZE],i,charsFound;
printf("Enter a line of text(empty line to quit): ");
while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
printf("Enter a character to search: ");
search=getchar();
charsFound=CharIsAt(array,search,found,SIZE);
printf("Entered text: ");
fputs(array,stdout); //Prints text inputted
printf("Character being searched for: %c\n",search); //Prints character being searched for
printf("Character found at %d location(s).\n",charsFound); //Prints # of found characters
//Prints the location of the characters found relative to start of line
for (i=0;i<charsFound;i++)
printf("'%c' was found at %d\n",search,found[i]);
if (fgets(array,SIZE,stdin)==NULL) //Makes loop re-prompt
break;
printf("\nEnter a line of text(empty line to quit): ");
}
return 0;
}
int CharIsAt(char *pStr,char ch,int loc[],int mLoc){
//Searches for ch in *pStr by incrementing a pointer to access
//and compare each character in *pStr to ch.
int i,x;
for (i=0,x=0;i<mLoc;i++){
if (*(pStr+i)==ch){
//Stores index of ch's location to loc
loc[x]=i;
x++; //Increment for each time ch was counted in pStr
}
}
//Returns the number of times ch was found
return x;
}
Related
I am trying to write a program that takes in 5 characters then takes in a number and a letter and switches the character at the index/number to the new character. I think I have it but it is not working and defaulting the number to 0.
Also, is there a way to get both inputs at the same time?
char str[5];
int index;
char temp;
printf("Enter five characters\n");
scanf("%s", str);
printf("Please enter a number.\n");
scanf("%d", &index);
printf("Please enter a letter.\n");
scanf("%s", &temp);
str[index - 1] = temp;
printf("The five characters are now %s\n", str);
accessing the char array with the index variable is giving me the first element always.
FYI: I haven't code in C for a long, long time; however, I did run this code below successfully. You might have to review it and fix other things I might have missed.
First, we will change the first scanf by indicating we want only 5 characters scanf("%5c", str); and I'm indicating we want the last position in the array to have.
Next, we will do a for loop because we want to only accept an index between 1 to 5.
Finally, and this is important, we change the scanf to get one character; however, this isn't intuitive as before, because you need a space before the character indicator: scanf(" %c", &temp);
Code:
#include <stdio.h>
int main()
{
char str[5];
printf("Enter five characters\n");
scanf("%5c", str);
int index = -1;
while (index < 1 || index > sizeof(str)){
printf("Please enter a number 1 to %d.\n", (int) sizeof(str));
scanf("%d", &index);
}
char temp;
printf("Please enter a letter.\n");
scanf(" %c", &temp);
str[index - 1] = temp;
printf("The five characters are now %s\n", str);
return 0;
}
Result:
Enter five characters
12345
Please enter a number 1 to 5.
1
Please enter a letter.
x
The five characters are now x2345
...Program finished with exit code 0
Press ENTER to exit console.
#include <stdio.h>
int main()
{
char str[5];
int index;
char temp;
printf("Enter five characters\n");
scanf("%s", str);
printf("Please enter a number.\n");
scanf("%d", &index);
printf("Please enter a letter.\n");
scanf(" %c", &temp);
str[index - 1] = temp;
printf("The five characters are now %s\n", str);
return 0;
}
Output:
Enter five characters
12345
Please enter a number.
2
Please enter a letter.
x
The five characters are now 1x345
Press any key to continue . . .
I have a for loop, which I want to get the input from the user and print the associated ascii value. But it only asks for the user input in the second iteration, which is followed and preceded by the output 10. I tried to get rid of new-line characters, but it still prints out 10.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: \n");
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
Maybe simpler (though using scanf() for user input is not recommended)
scanf(" %c", &character);
// ^ skip otional leading whitespace
Your whole program using fgets() for user input (and my indentation, spacing, style; sorry)
#include <stdio.h> // printf(), fgets()
#include <stdlib.h> // strtol()
int main(void) {
int number;
char buffer[100]; // space enough
printf("Enter the number:");
fgets(buffer, sizeof buffer, stdin);
number = strtol(buffer, 0, 10); // error checking missing
for (; number > 0; number--) {
printf("Give a char: ");
fgets(buffer, sizeof buffer, stdin); // reuse buffer, error checking missing
if (buffer[0] != '\n') {
printf("The associated ascii value of '%c' is %i.\n", *buffer, *buffer);
}
}
return 0;
}
This should solve your problem. getchar() will read the extra newline character from buffer.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: ");
getchar();
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
regarding;
scanf("%c", &character);
the first time through the loop the '\n' is input.
on all following passes through the loop, the scanf() fails, so the value in character does not change.
This is a prime example of why your code should be error checking.
for instance, to error check the call to scanf():
if( scanf("%c", &character) != 1 )
{
fprintf( stderr, "scanf for a character failed\n" );
break;
}
the 1 is because the scanf() family of functions returns the number of successful: input format conversion specifiers or EOF and it is best to assure the 'positive' status.
I tried to execute the following simple code in ubuntu 15.10 But the code behaves odd than expected
#include<stdio.h>
int main(){
int n,i=0;
char val;
char a[20];
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%c",&val);
int count=0;
for(i=0;i<20;i++){
if(a[i]==val){
printf("\n%c found at location %d",val,i);
count++;
}
}
printf("\nTotal occurance of %c is %d",val,count);
return 0;
}
output:
--------------------------
Enter the value : 12345678
Enter the value to be searched :
Total occurance of is 0
The second scanf to get the value to be searched seems not to be working. The rest of the code executes after the first scanf without getting input second time.
After first scanf(), in every scanf(), in formatting part, put a whitespace
So change this
scanf("%c",&val);
into this
scanf(" %c",&val);
Reason is, scanf() returns when it sees a newline, and when first scanf() runs, you type input and hit enter. scanf() consumes your input but not remaining newline, so, following scanf() consumes this remaining newline.
Putting a whitespace in formatting part makes that remaining newline consumed.
You can use fgets():
#include<stdio.h>
int main() {
int n, i = 0;
char val;
char a[20];
printf("\nEnter the value : ");
fgets(a, 20, stdin);
printf("\nEnter the value to be searched : ");
scanf("%c", &val);
int count = 0;
for (i = 0; i < 20; i++) {
if (a[i] == val) {
printf("\n%c found at location %d", val, i);
count++;
}
}
printf("\nTotal occurance of %c is %d", val, count);
return 0;
}
or clear stdin:
#include<stdio.h>
void clearstdin(void) {
int c;
while ((c = fgetc(stdin)) != EOF && c != '\n');
}
int main() {
int n, i = 0;
char val;
char a[20];
printf("\nEnter the value : ");
scanf("%s",a);
clearstdin();
printf("\nEnter the value to be searched : ");
scanf("%c", &val);
int count = 0;
for (i = 0; i < 20; i++) {
if (a[i] == val) {
printf("\n%c found at location %d", val, i);
count++;
}
}
printf("\nTotal occurance of %c is %d", val, count);
return 0;
}
Also, see C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%d",&val); // here is different
i don't know why, but code above working...
scanf("%d",&val);
You can use " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.
This code works well for words with less than five letters: (but not for higher)
#include <stdio.h>
int main(void)
{
const int size = 5;
char str1[size], str2[size], str3[size];
printf("Type word1: ");
scanf("%s", str1);
printf("Type word2: ");
scanf(" %s", str2);
printf("Type word3: ");
scanf(" %s", str3);
printf("First chars: '%c', '%c' e '%c'.\n", str1[0], str2[0], str3[0]);
return 0;
}
The only way to run correctly would increase the 'size' variable? I wonder if it is possible to work properly with larger words without necessarily increasing the 'size' variable.
This will get you close
Just save 1st char
#include <stdio.h>
int main(void)
{
char str[3];
printf("Type word1: ");
scanf(" %c%*s", &str[0]);
printf("Type word2: ");
scanf(" %c%*s", &str[1]);
printf("Type word3: ");
scanf(" %c%*s", &str[2]);
printf("First chars: '%c', '%c' e '%c'.\n", str[0], str[1], str[2]);
return 0;
}
regarding this kind of line: 'scanf("%s", str1);'
1) the scanf format string needs to limit the number of characters input,
otherwise (in this case)
inputting a word longer than 4 char will result in a buffer overrun
2) always check the returned value from scanf
to assure the input/conversion operation was successful.
3) I would strongly suggest using fgets() and sscanf()
then
--the max number of characters is limited by a fgets() parameter,
--the string is null terminated,
--the newline is part of the string,
so will need to be overlayed with '\0'
4) in the user prompts,
I would use:
printf( "\nUsing %d or less characters, enter a string:", argv[1] );
where argv[1] is a command line parameter that indicates the max string length.
(be sure to allow for the nul terminator byte)
Have to replace a user input character with another user input character and print the string . What am i doing wrong ?
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char a,b,str[100];
printf("Enter the string");
gets(str);
//asking for replacement
printf("enter the character to be replaced");
scanf("%c",&a);
// which letter to replace the existing one
printf("enter the character to replace");
scanf("%c",&b);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
else
continue;
}
printf("the new string is");
puts(str);
}
scanf("%d",&a);
You get an integer ? not a character ? If it is a character, then you should use %c instead of %d
Add getchar() function between the two scanf().
Like
#include<stdio.h>
main()
{
int i;
char a,b,str[100];
printf("Enter the string");
gets(str);
//asking for replacement
printf("enter the character to be replaced");
scanf("%c ",&a);
//Get the pending character.
getchar();
// which letter to replace the existing one
printf("enter the character to replace");
scanf("%c",&b);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
else
continue;
}
printf("the new string is");
puts(str);
}
The problem is when you give a character and pressed enter, newline will acts as one character and it will be get by the next scanf. To avoid that the getchar() is using.
Another Way:
Give space before the access specifier on character to replace,
Like
scanf(" %c",&b);
But before remove that getchar().
#include<stdio.h>
#include<conio.h>
int main() //main returns an int
{
int i;
char a,b,str[100];
printf("Enter the string\n");
fgets(str,sizeof(str),stdin);//gets is dangerous
printf("Enter the character to be replaced\n");
scanf(" %c",&a); //space before %c is not neccessary here
printf("Enter the character to replace\n");
scanf(" %c",&b); //space before %c is compulsory here
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
//else //This part is not neccessary
//continue;
}
printf("The new string is ");
puts(str);
return 0; //main returns an int
}
I've used fgets because gets is dangerous as it does not prevent buffer overflows.
The space before %c in the scanf is to skip blanks,i.e,spaces,new-lines etc and it isn't needed in the first scanf is that fgets also consumes the new-line characters and puts it into the buffer.
The reason that the else continue; isn't needed is that the loop is going to check the condition as it has reached the end of the loop body.
I've used int main() and return 0 because as per the latest standards,it should
Finally,you have an unused header conio.h in your program.
Try this, it worked for me:
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char a,b,str[100];
printf("Enter the string: ");
gets(str);
//asking for replacement
printf("enter the character to be replaced: ");
a = _getch();
printf("\n%c", a);
// which letter to replace the existing one
printf("\nenter the character to replace: ");
b = _getch();
printf("\n%c", b);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
else
continue;
}
printf("\nthe new string is: ");
puts(str);
}
You can remove the else block. It won't affect anything.