#include <stdio.h>
int stringLength (char *text)
{
int count = 0;
while (*text != '\0')
{
count++;
text++;
}
return count;
}
int main()
{
char str[25];
int length;
printf("ENter string: ");
scanf("%s", &str);
length = stringLength(str);
if (length > 25)
{
printf("Invalid\n");
printf("Enter string: ");
scanf("%s", &str);
}
printf("Your string is: %s and its %d long", str, length);
return 0;
}
If the first input is wrong (over 25) it will remember that number (length) and when I input another string it will add the numbers together. How do I fix it so it goes from beginning? So it counts the next string from start?
You can't in this way. Your code has at least two problems:
You don't have to use the & when you pass a string to scanf, because str is already a pointer (search the equivalence pointer and array in C).
If you insert more than 25 what is happening is a buffer overflow and your program presents an undefined behavior after the scanf. You may want to consider a different and safer approach to read from keyboard (e.g. fgets)
char str[25];
Can only contain a string of 24 char + NULL. Use a width specifier to limit input to 1 less than buffer size when scanning strings into scanf().
Replace the if() branch with a while() loop:
length = stringLength(str);
while(length > 24)// an array of 25 elements can only accommodate 24 characters + NULL
{
printf("Invalid\n");
printf("Enter string: ");
//use input limiter of 24 for char str[25];
scanf("%24s", str);//remove & (for all scanf scanning a string)
length = stringLength(str);
}
Related
I need to check the length of an input using the function scanf().
I'm using an array of char (%s) to store the input, but I wasn't able to check the length of this input.
this below is the code:
#include <stdio.h>
char chr[] = "";
int n;
void main()
{
printf("\n");
printf("Enter a character: ");
scanf("%s",chr);
printf("You entered %s.", chr);
printf("\n");
n = sizeof(chr);
printf("length n = %d \n", n);
printf("\n");
}
it's giving me back that "length n = 1" for the output in each case I've tried.
How can I check the length of the input in this case?
Thank You.
to check the length of input char array (%s) using scanf()
Do not use the raw "%s", use a width limit: 1 less than buffer size.
Use an adequate sized buffer. char chr[] = ""; is only 1 char.
Use strlen() to determine string length when the input does not read null characters.
char chr[100];
if (scanf("%99s", chr) == 1) {
printf("Length: %zu\n", strlen(chr));
}
Pedantic: Use "%n" to store the offset of the scan if code might read null characters (this is rarely or nefariously encountered).
char chr[100];
int n1, n2;
if (scanf(" %n%99s%n", &n1, chr, &n2) == 1) {
printf("Length: %d\n", n2 - n1);
}
sizeof is a compile time unary operator which can be used to compute the size of its operand.if you want to calculate the length of the string the you have to use strlen().like this
#include <stdio.h>
#include <string.h>
int main()
{
char Str[1000];
printf("Enter the String: ");
if(scanf("%999s", Str) == 1) // limit the number of chars to sizeof Str - 1
{ // and == 1 to check that scanning 1 item worked
printf("Length of Str is %zu", strlen(Str));
}
return 0;
}
Is there a simple way to make sure you're reading a character through scanf. If it were an integer I'd use a do while loop
do{
printf("enter a number");
fehler = scanf(" %d", &x);
getchar();
} while(fehler!=1);
But I'm not fully sure what to do if the input is meant to be a string. I know the alphabets are stored as ASCII values but the if constraints in the while statement don't seem to be working(unless I'm doing it wrong)
char * temp2;
temp2 = malloc(sizeof(string));
do{
printf("PLease enter a string: ");
scanf(" %s", temp2);
getchar();
} while(temp2 <= 'A' && temp2 <= 'z')
You can't compare a string to a single character. You have to loop through the entire string, checking every character.
#include <ctype.h>
int is_alphabetic(char *str) {
for (int i = 0; str[i]; i++) {
if (!isalpha(str[i])) {
return 0;
}
}
return 1;
}
...
do{
printf("Please enter an alphabetic string: ");
scanf(" %s", temp2);
getchar();
} while(!is_alphabetic(temp2));
You see printf and scanf work independently. Whatever you store be it a character or number is stored in form of a number. Now it depends on the printf function what it demands.
Eg.: If you store 'a' at a location, the number 97 is stored. Now if you print a number it prints 97 and if you demand a character it gives a.
#include <stdio.h>
int main()
{
int i = 97;
printf("%d \n", i);
printf("%c", i);
return 0;
}
See the results. Further char, int , long int are just data types which specify the number of bits that would be resrved for the inputs for the variable.
Execute this program and you'll understand:
#include <stdio.h>
int main()
{
int i;
for (i=97; i <=200 ; i++)
{
printf("%d %c,\t",i,i);
};
return 0;}
This will show you a nmber when printed as a number and then the SAME number read as character.
Note there are no markers in memory to store which type of data it is. It is straightforward stored as number.
scanf is absolutely the wrong tool for this. But if you want to read only alphabetic characters, you can do it easily enough with something like:
char s[32];
if( 1 == scanf(" %31[a-zA-Z]", s) ){ ... }
The %31[a-zA-Z] conversion specifier will match only the literal characters a thru z and A thru Z, and will only consume up to 31 characters of input. You must always use a field width modifier with %s or %[] conversion specifiers to avoid an overflow.
I read chars until '\n', convert them to int and sum the numbers until the result is only one digit.
I can't use mod or .
The first run went well, but the second one keep running and not waiting to \n.
any reason for keeping the '\n'?
#include<stdio.h>
int main(){
char str[8], conv_str[8],c;
int i,val,ans = 0;
while(1){
printf("Enter 8 values(0-9) :\n");
scanf("%[^\n]", str); // Scan values to str untill \n
for(i = 0;i < 8;i++){
val = str[i]-48; //convert from asci to int
ans += val;
}
while(ans > 9){
// itoa convert int to string, str(the input) is the buffer and 10 is the base
itoa(ans,conv_str,10);
ans = (conv_str[0]-48) + (conv_str[1]-48) ;
}
printf("the digit is: %d", ans);
printf("\ncontinue? (y/n)\n");
scanf("%s", &c);
if (c == 'n')
break;
memset(str, 0, sizeof(str));
}
return 0;
}
TIA
You have multiple problems in the code. Some of them are
scanf("%s", &c); is wrong. c is a char, you must use %c conversion specifier for that.
You never checked for the return value of scanf() calls to ensure success.
While scanning for character input, you did not clear the buffer of any existing inputs. Any existing character, including a newline ('\n') already present in the buffer will be considered as a valid input for %c. You need to clear the buffer before you read a character input.
I want to ask how to prevent a corruption in the array buffer, This is my code.
#include <stdio.h>
#define buffSize 20
void clrscr() {
for(int i = 0; i < 25; ++i)
putchar('\n');
}
int main() {
char arr1[buffSize];
char arr2[buffSize];
do {
clrscr();
printf("String 1 :\n");
scanf("%[^\n]", &arr1); fflush(stdin);//prompt first string
} while(strlen(arr1) > buffSize);
do {
clrscr();
printf("String 1: %s\n\n", arr1);//The problem is here
printf("String 2 : ");
scanf("%[^\n]", &arr2); fflush(stdin);
} while(strlen(arr2) > buffSize);
return 0;
}
Say that we have inputted the first arr of char correspondingly to the buffSize, then we input the second arr of char which has inputs that exceeds the limitation of the buffSize. The arr1 will be assigned with some of the characters that was inputted above the arr2 size. How to prevent this ?
fflush(stdin) is undefined behavior, it is generally only defined for output streams.
Try this instead :
while ((c = getchar()) != '\n' && c != EOF);
If you are trying to limit the number of characters that scanf() attempts to read, you can use :
scanf("%19[^\n]", arr2);
Note that the number specified in scanf() must be one less than your buffer size to save room for '\0' and it should be arr1 and arr2, no &. Array names are already pointers to the beginning of the array.
This program is supposed to convert the array of chars (string) into an array of ints by subtracting 97 from their ascii value (the input should be lower case cause a has an ascii value of 97). So if i enter the string abcd i should get 0123 but instead I somehow get this: 012134513789. I can't figure out where the problem is.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void userEnter(int*pattern, int n);
int main(void)
{
int n, i;
printf("What is the length of the array: ");
scanf("%d",&n);
int pattern[n];
printf("Enter the char array: ");
userEnter(pattern, n);
printf("The int array is: ");
for(i=0;i<n;i++)
{
printf("%d",pattern[i]);
}
printf("\n");
}
void userEnter(int*pattern, int n)
{
char input[n];
scanf("%s", input);
int i;
for(i = 0; i < n-1; i++)
{
pattern[i] = input[i]-97;
}
}
char input[n];
scanf("%s", &input);
should be
char input[n+1];
scanf("%s", input);
input is equivalent to &input[0]
You should also exit the for loop in userEnter when you encounter the nul character that ends the user-entered string. e.g. with something like
char* p = input;
while (*p != '\0') {
*pattern = (*p) - 'a';
p++;
pattern++;
}
As KingsIndian points out, you also need to increase the size of your input buffer. At present, you overflow that buffer and overwrite the loop counter i;
The length parameter n includes one character for null as well. So, if you input length for n 4 then you can only input 3 characters, for example abc because the 4th is for the null.
So you should change the declaration accordingly:
Change:
char input[n];
to:
char input[n+1];
Note that variable length arrays are allowed only since C99.