isdigit and arrays in C - c

I am trying to create a function that takes the users input as a string then I use the atoi() function. I have it working hard coded but it will not work when I put it into a for loop in my void getUserInput() function:
for(i = 0; i < 3; i++)
{
switch(num)
{
case 1:
printf("Enter number one: ");
break;
case 2:
printf("Enter number one: ");
break;
case 3:
printf("Enter number one: ");
break;
}
fgets(input, 50, stdin);
if(isdigit(input[i]))
{
if(isdigit(input[i + 1]))
{
if(isdigit(input[i + 2]))
{
printf("Error\n");
}
else
{
...
I know that the way I incremented the isdigit() is the problem but I do not know another way how to check the first char, then second then third from the users input. Any suggestions on how to increment it?
by the way if this helps:
char input[50];

You should use logical operators instead of nested if's:
if(isdigit(input[i]) && isdigit(input[i + 1]) && isdigit(input[i + 2]))
Even if this is equivalent, it makes code easier to read and understand. But this is not the problem. You are sure the input has 3 characters, followed by NUL? You should check for this too.
Besides what I said, is pretty hard to find the real problem without making assumptions, as your code is not complete.

Assuming input array is character array.
you can do like this :
int len, j;
len = strlen(input);
for(j=0; j<len; j++){
if(isdigit(input[j]){
// do what you want
}else{
// do something else you want
}
}
Make sure you have included <string.h> and <ctype.h>.

If reading input via fgets() the "string" returned might carry a trailing '\n' for IXish systems or a combination of '\n' and '\r' on other systms, which will make atoi() choke.
To get around this either chop of the trailer by doing:
{
char * pc;
while (pc = strpbrk(input, "\n\r"))
{
*pc = '\0';
}
}
or get rid of using atoi() and go for strtol(). atoi() is evil dump/unusable at least if you want to be able to successfully read in 0 as it returns 0 on error.

Related

How to count the length of each word in a string of characters

I'm a beginner programmer and im trying to solve some exercises and i needed some help with one of them.
The exercise goes like this:
We need to input a string of characters , read it and print out the length of each word.
This is what i did
int main()
{
char str[N+1+1];
int i=0;
int pos=0;
int wordlen=0;
int word[60]={0,};
printf("Please enter the string of characters: ");
gets(str);
while(i<strlen(str))
{
if(!isalpha(str[i]))
{
wordlen=0;
i++;
}
if(isalpha(str[i]))
{
wordlen++;
i++;
pos=i;
}
word[pos]=wordlen;
wordlen=0;;
i++;
}
for(i=0;i<20;i++)
{
if(word[i]==0) // here im just trying to find a way to avoid printing 0's but you can ignore it if you want
{break;}
else
printf("%d ",word[i]);
}
return 0;
}
The problem is that when i try to compile it for example: I input "hi hi hi" its supposed to print 2 2 2 but instead it's printing nothing.
Can i ask for some help?
I failed to follow OP's logic.
Perhaps begin again?
End-of-word
To "count the length of each word", code needs to identify the end of a word and when to print.
Detecting a non-letter and the current word length > 0 indicates the prior character was the end of a word. Note that every C string ends with a non-letter: '\0', so let us iterate on that too to insure loop ends on a final non-letter.
int word_length = 0;
int strlength = strlen(str); // Call strlen() only once
while (i <= strlength) {
if (isalpha(s[i])) {
word_length++;
} else {
if (word_length > 0) {
printf("%d ", word_length);
word_length = 0;
}
}
}
printf("\n");
gets()
gets() is no longer in the C library for 10 years as it is prone to over-run. Do not use it.
we are supposed to use gets. is unfortunate and implies OP’s instruction is out-of-date. Instead, research fgets() and maybe better instruction material.
Advanced
is...() better called as isalpha((unsigned char) s[i]) to handle s[i] < 0.
In general, better to use size_t than int for string sizing and indexing as the length may exceed INT_MAX. That is not likely to happen with OP's testing here.

c programming - printing sentences

this is my first time using this site as well as learning c programming.
I'm trying to write a code which lets a user type in a sentence and the code prints it back out.
My attempt:
#include<stdio.h>
int main()
{
char array[1000];
printf("Please enter a phrase: ");
int index = 0;
while(array[index]!= '\0')
{
scanf("%c",&array[index]);
++index;
}
index = 0;
while(array[index]!= '\n')
{
printf("%c",array[index]);
++index;
}
}
I can't find the reason to why this code does not work.
You can get expected output using your concept also.. Try something using following code.
#include<stdio.h>
int main()
{
char array[1000];
printf("Please enter a phrase: ");
int index =0;
scanf("%c",&array[index]);
while(array[index]!='\n')
{
scanf("%c",&array[++index]);
}
index=0;
while(array[index]!= '\n')
{
printf("%c",array[index]);
++index;
}
printf("\n");
}
Okay, so first and foremost you'll need to initialize all your array. If you don't, the user input will print along with lots of meaningless garbage.
Secondly, the test portion of your first while loop checks for a null character which will never exist because "array[]" is just a simple character array (not a string) therefore, a call to scanf() doesn't insert the null character at the end. This causes an infinite loop.
Thirdly, your first while loop should be a do-while so that you first read a character, then test the character, otherwise if the "index" variable increments first...
Lastly, I posted the code that i used to get it to run using the method that you chose. However, as an alternative to the method you chose, the c standard library has the gets() function, which will allow you to read an entire line of input and return the string entered (actually it returns a pointer to the character array created but i think you catch my drift), and the puts() function which prints a string pointed to by the pointer used as an argument.
For more info on this problem in general, including gets() and puts(), refer to "C Programming A Modern Approach" by K.N. King, Chapter 13: Strings.I hope this helps.
Happy Coding!! :)
#include <stdio.h>
int main()
{
int index = 0;
char array[1000];
while(index < 1000){
array[index] = '0';
index++;
}
printf("Please enter a phrase: ");
index = 0;
do {
scanf("%c", &array[index]);
} while(array[index] != '\n' && index++ < 1000);
index = 0;
while(index < 1000)
printf("%c", array[index++]);
}
I think your looking for this:
#include<stdio.h>
int main() {
char array[1000];
printf("Please enter a phrase: ");
scanf ("%[^\n]%*c", array);
printf("\n%s", array);
return 0;
}

Disabling characters other than numbers in scanf in C

The problem I have is that I want to disable the user the possibility of putting character instead of number inside my program and optionally printing the message "it is disabled". It should ask for the value of the same variable. I tried to do this using this:
scanf(" %[0-9]d",&x);
and this:
else
result = scanf("%*s");
but it still does not work. What should I look for? I've searched internet, but I've only found solutions for C++ in which cin was used and unfortunately it does not work in C at all.
You can try something like this:
char c[SIZE];
int i;
// While the string is not a number
while(fgets(c, SIZE , stdin) && !isAllDigit(c));
where isAllDigit is:
int isAllDigit(char *c){
int i;
for(i = 0; c[i] != '\0' && c[i] != '\n'; i++) // Verify if each char is a digit
if(!isdigit(c[i])) // if it this char is not a digit
return 0; // return "false"
return 1; // This means that the string is a number
}
scanf isn't used much anymore as it is completely unsuitable for keyboard input. The basic scheme these days is to do fgets() + validate + sscanf() in a loop.

How do I check length of user input in C?

I'm kind of new to C, and the input reading is really confusing me. I'm trying to initialize an array of size 4, but sometimes the user will enter valid input of 3. In Java, I could check the length of the input and add conditionals, but I'm not sure how this works in C.
main(void){
char str[N];
int i;
for(i = 0; i < N; i++){
scanf("%c", &str[i]);
}
for(i = 0; i < N; i++){
printf("%c\n", str[i]);
}
}
Right now, if I input 4 or more, it works fine. If I input 3, it breaks. I'd like it to handle both 3 or 4 characters.
Actually, the root of the problem is: I'm trying to figure out a way in C to read in a 24-hour-clock time, and add it to a 24-hour-clock duration. Should I be approaching this an entirely different way?
Thanks,
The short answer is: you can't.
Using scanf() is particularly dangerous because of this if you want to read in a string (%s); if the user enters more input than your buffer can hold, you have a buffer overflow on your hands.
fgets() on the other hand, allows you to specify the max number of bytes you will read, preventing you from overflowing the buffer.
Here's a quick example on how you'd write a function for some input that verified that the input was within a specified length and was a complete line (ending with \n - this routine discards the \n from the input):
void getInput(char *question, char *inputBuffer, int bufferLength)
{
printf("%s (Max %d characters)\n", question, bufferLength - 1);
fgets(inputBuffer, bufferLength, stdin);
if (inputBuffer[strlen(inputBuffer) -1] != '\n')
{
int dropped = 0;
while (fgetc(stdin) != '\n')
dropped++;
if (dropped > 0) // if they input exactly (bufferLength - 1)
// characters, there's only the \n to chop off
{
printf("Woah there partner, your input was over the limit by %d characters, try again!\n", dropped );
getInput(question, inputBuffer, bufferLength);
}
}
else
{
inputBuffer[strlen(inputBuffer) -1] = '\0';
}
}
int main()
{
char firstAnswer[10];
getInput("Go ahead and enter some stuff:", firstAnswer, 10);
printf("Okay, I got: %s\n",firstAnswer);
}
scanf() allows the use of maximum width specifiers:
So scanf("%3s", buffer) reads at most 3 characters + 1 NUL terminator.

Counting characters in C

I'm trying to write a program that counts all the characters in a string. I originally had it, but then realized I can't count spaces. I can't see why this does not work.
for(m=0; z[m] != 0; m++) {
if(z[m] != ' ') {
charcount ++;
}
}
Any assistance appreciated.
Edit* Does it make a difference if the input(strings) are being scanned in like this? And yes, everything is initialized. I've tried printing what z[m] evaluates too and it isn't the actual value of the string at "m", I think this is the problem.
for(j=0; j<7; j++){
printf("Enter a string:\n");
scanf("%s", z);
for(m=0; z[m] != 0; m++){
if(z[m] != ' '){
charcount ++;
}
}
You need to initialize charcount. Other than that, it should work, provided that z is a zero-terminated array of characters and m is an int or similar. I would probably write just z[m] rather than z[m] != 0 (since !0 = true and 0 = false), but both work. There are more efficient ways of doing it (although these days I bet a compiler will handle converting this into a pointer-based loop for you).
Here's a complete, correct example with minimal edits:
const char * z = "testing one two three";
int m;
int charcount;
charcount = 0;
for(m=0; z[m]; m++) {
if(z[m] != ' ') {
charcount ++;
}
}
If you're using a String class of some kind rather than an old-fashioned C null-terminated array, you'll want to look at that class for how to loop through it.
All of the above also assumes you're dealing with ASCII strings. If you're dealing with UTF-encoded strings, you have to handle multi-byte characters.
Re your edit: It makes a big difference: scanf will stop on the first blank (I'd forgotten that). It might make an even bigger difference than that, though, if you're not declaring z correctly. (I'd also recommend using a field width when using scanf for reading strings [or avoiding scanf entirely]; otherwise, you have no control over the number of chars it will try to store, and so in theory, no buffer will ever be big enough to avoid an overflow. More here: http://www.crasseux.com/books/ctutorial/String-overflows-with-scanf.html)
You can use strlen()
I'd suggest using a while loop, and to use more meaningful variable names
m = textIndex
z = text
Something like this would work
while (text[textIndex] != 0x00)
{
textIndex++;
}
Instead of using scanf, try fgets like so:
char input[256];
fgets(input, sizeof(input), stdin);
fgets will read an entire line from a file. As such, passing stdin as the file handle will make it read from standard input, which in most cases will be bound to the console. One thing to watch out for, though, is that the string you get from fgets might include the newline character. Rather than explicitly checking your strings for inequality with the space character (' '), I suggest using the isspace function from ctype.h, which will check for various forms of whitespace (including a regular space and newline).
Here is a complete, runnable example:
#include <stdio.h>
#include <ctype.h>
int count_nonspace(const char* str)
{
int count = 0;
while(*str)
{
if(!isspace(*str++))
count++;
}
return count;
}
int main()
{
char input[256];
fgets(input, sizeof(input), stdin);
printf("%d\n", count_nonspace(input));
}
Yes, there is a difference on input-scan with scanf:
scanf("%s", z);
...
if(z[m] != ' '){
scanf("%s"...) always breaks at space-character, therefore your if ever is true. Better you use fgets to read from stdin,
#define MAXINPUT 80
char line[MAXINPUT];
for(j=0; j<7; j++) {
printf("Enter a string:\n");
if( fgets( line, 80, stdin ) )
{
char *c=line;
if( strchr(line,'\n') ) *strchr(line,'\n')=0;
while( *c )
{
if( *c!=' ' )
++charcount;
++c;
}
}
}
Or if you want WHITE -spaces then take
#include <ctype.h>
...
if( !isspace(*c) )
this seems to work for me, its a simple 30 line code that is in a loop and can detect the letter of choice for the chosen string/sentence/word the user has inputted.
#include <stdio.h>
#include <string.h>
int main(){
while(true){
char string[100];
char letter[100];
int count = 0;
printf("Enter a word/sentence:\n");
scanf(" %[^\n]s",string);
printf("Enter a letter:\n");
scanf(" %c",&letter); //when using scanf for a sentence/word or character, always include a space afterwards.
//Counts each character except space
for(int i = 0; i < strlen(string); i++) {
if(string[i] == letter[0]){
count++;
}
}
//Displays the total number of characters present in the given string
printf("Total number of characters in the string: %d\n", count);
printf("%s\n",string);
}
return 0;
}

Resources