Validating input from Integers - c

Thank you guys for answering my first question, but I have another one. I have this code here
that uses strtol() function. It works, but the problem is that if I enter one of the three options: (d 2) its considered as a string, and if Input (2d) its a string, and (d2) is a string. Is there a way to detect the numbers within the array?
char userInput[256];
char *end;
printf("Please enter your name: ");
scanf("%s", userInput);
int userName = strtol(userInput, &end, 10);
if (!*end)
{
printf("You have enter an int");
}
else
{
printf("You have entered a string");
}

If you really just need to check to see if string has numbers in it, this will do:
int has_ints(char * str) {
const int len = strlen(str);
int i;
for (i = 0; i < len; i++) {
if (str[i] <= '9' && str[i] >= '0') {
return 1;
}
}
return 0;
}

I did this:) works quite beautifully!
int exit = 0;
int i;
while (exit != 1)
{
char userInput[256] = {0};
int asciiCode[256];
int zeroCounter = 0;
int letterProof = 0;
int numberProof = 0;
int specicalCharactersProof = 0;
printf("\nPlease enter your name: ");
fgets(userInput, 256, stdin);
for (i = 0; i < 256; i++)
{
asciiCode[i] = userInput[i];
if (asciiCode[i] == 0)
{
zeroCounter++;
}
}
int reSize = (256 - zeroCounter);
for (i = 0; i < reSize; i++)
{
if (asciiCode[i] >= '0' && asciiCode[i] <= '9')
{
numberProof = 1;
}
else if ((asciiCode[i] >= 'a' && asciiCode[i] <= 'z') || (asciiCode[i] >= 'A' && asciiCode[i] <= 'Z'))
{
letterProof = 1;
}
else if ((asciiCode[i] >= '!' && asciiCode[i] <= '/') || (asciiCode[i] >= ':' && asciiCode[i] <= '#') || (asciiCode[i] >= '[' && asciiCode[i] <= '`') || (asciiCode[i] >= '{' && asciiCode[i] <= '~'))
{
specicalCharactersProof = 3;
}
}
if (letterProof == 1 && numberProof == 0 && specicalCharactersProof == 0)
{
printf("\nWelcome %s\n", userInput);
exit = 1;
}
else
{
printf("\nInvalid Input.\n");
}
}
return(0);
}

Related

Find index of word in string

I want to write a function which will find index of word in string.
For example if string is
This is word.
my function for string "word" should return number 3.
Note: functions from string.h library and auxiliary strings are not allowed.
How could I do this in C?
I can't think of a solution better than this (though there might be better ones).
#include <stdio.h>
int main() {
char word[] = "This is a word";
int flag = 0, space = 0, pos = -1;
for (int i = 0; word[i] != '\0'; i++) {
if (flag == 1) {
break;
}
for (int j = 0; word[j] != '\0'; j++) {
if (flag == 1) {
break;
}
else if (word[j+1] == '\0' || word[j+2] == '\0' || word[j+3] == '\0') {
break;
}
else {
if (word[j] == 'w' && word[j+1] == 'o' && word[j+2] == 'r' && word[j+3] == 'd') {
flag = 1;
pos = j;
}
}
}
}
for (int i = 0; word[i] != '\0'; i++) {
if (word[i] == ' ' || word[i] == '!' || word[i] == '#') {// And many more symbols
fchars++;
}
else {
break;
}
}
if (flag == 1 && pos-1 > 0 && word[pos-1] == ' ') {
for (int i = 0; i < pos; i++) {
if (word[i] == ' ') {
space++;
}
}
printf("Found at position = %i\n", space+1-fchars);
}
else {
printf("Not found!\n");
}
}
You can split the sentence by space to get the words and then match each word in the sentence with the word you want to match
Please check this modified code:
#include<stdio.h>
int main()
{
char word[] = "word";
char string[100];
gets(string);
int curWordStart = -1;
int curWordEnd = -1;
int wordCount = 0;
int i = 0;
for (i = 0; string[i] != '\0'; i++)
{
if (string[i] == ' ')
{
int curWordLength = curWordEnd - curWordStart + 1;
if (curWordStart != -1 && curWordLength > 0)
{
wordCount++;
int foundMatch = 1;
int j;
int k = 0;
for (j = curWordStart; j <= curWordEnd; j++) {
if (word[k] == '\0') {
foundMatch = 0;
break;
}
if (word[k] != string[j])
{
foundMatch = 0;
break;
}
k++;
}
if (word[k] != '\0')
{
foundMatch = 0;
}
if (foundMatch == 1)
{
printf("%d\n", wordCount);
}
}
curWordStart = -1;
curWordEnd = -1;
}
else if ((string[i] >= 'a' && string[i] <= 'z') || (string[i] >= 'A' && string[i] <= 'Z'))
{
if (curWordStart == -1) {
curWordStart = i;
}
curWordEnd = i;
}
}
int curWordLength = curWordEnd - curWordStart + 1;
if (curWordStart != -1 && curWordLength > 0)
{
wordCount++;
int foundMatch = 1;
int j;
int k = 0;
for (j = curWordStart; j <= curWordEnd; j++) {
if (word[k] == '\0') {
foundMatch = 0;
break;
}
if (word[k] != string[j])
{
foundMatch = 0;
break;
}
k++;
}
if (word[k] != '\0')
{
foundMatch = 0;
}
if (foundMatch == 1)
{
printf("%d\n", wordCount);
}
}
return 0;
}
It will print each position of the searched word in the sentence. If you want to just print the first one, you can easily modify it.
Here are steps to follow:
you must specify precisely what is a word in the string.
measure the length len of the word to search
define an int index = 1
in a loop, using a pointer p starting at the beginning of the string:
advance p past all word delimiters (spaces, punctuation or non letters?)
if p is at end of string return 0 (not found).
measure the length len1 of the current word in the string
if len1 == len and all bytes are identical to those of the word, return index
otherwise skip the word by advancing p by len1, increment index and continue the loop.
Here is an implementation:
#include <stddef.h>
int isletter(char c) {
/* assuming ASCII */
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
int word_index(const char *str, const char *word) {
const char *p = str;
size_t len, len1, i;
int index = 1;
for (len = 0; word[len]; len++)
continue;
for (;;) {
while (!is_letter(*p))
p++;
if (*p == '\0')
return 0;
for (len1 = 0; is_letter(p[len1]); len1++)
continue;
if (len1 == len) {
for (i = 0; i < len && p[i] == word[i]; i++)
continue;
if (i == len)
return index;
}
p += len1;
index++;
}
}

Movement for game character doesn't work at all

Here is the .c code from start to finish. I suspect it's an order of operations issue or something else.
The code is supposed to have a title screen where you can exit or play. If you hit play it renders a new char array in which you can move either left, right, or down (a/d/s). You get points for going down a row each time as well as going over 'P' spots on the array.
Once you hit y-coordinate 202 on the array as well as have positive points, you win and it renders a congrats char array. If you go negative in points (by hitting the '#' paces or the 'L' wall that goes down a row every 1/2 second) then you will lose and be told you lost in a new char array as well as be asked if you want to exit or play again.
And as mentioned before, the movement for the 'L's and the play character 'O' simply doesn't move.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
char quickchar(float delay);
void render();
void titleRender();
void renderLoss();
void renderWin();
int score();
char titlescreen[20][59] = { };
char diffdiff[20][46] = {
(Grid removed due to char limit)
};
char gameover[20][50] = {
(Grid removed due to char limit)
};
char gameboard[203][26] = {
(Grid removed due to char limit)
};
int playerx;
int playery;
int pts;
void entryRender();
void gameRender();
int main() {
int input;
char replay;
int lx;
int ly;
char walkin;
int gaming;
char titlechoice;
int diff;
int running;
lx = 0;
ly = 0;
running = 1;
playerx = 13;
playery = 5;
pts = 25;
gaming = 0;
while (gaming == 0) {
titleRender();
printf("\033[1;32m");
printf("\nPress 'p' to play or 'x' to exit!");
printf("\033[0m");
scanf(" %c", &titlechoice);
if (titlechoice == 'p') {
gaming += 4;
}
if (titlechoice == 'x') {
return 0;
}
}
while (gaming == 4) {
system("stty -echo raw");
render();
printf("\033[1;35m");
printf("Choose a direction: s/Down, a/Left, d/Right.\n\r");
printf("\033[0m");
walkin = quickchar(0.5);
scanf("%c", &walkin);
//obj behaviour
if (walkin == 's' &&
gameboard[playery +1][playerx] != '#' &&
gameboard[playery + 1][playerx] != '+' &&
gameboard[playery + 1][playerx] != '|' &&
gameboard[playery + 1][playerx] != '-') {
playery++;
pts += 5;
if (gameboard[playery + 1][playerx] == '#') {
pts -= 25;
}
if (gameboard[playery + 1][playerx] == 'P') {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery + 1][playerx] = '_';
}
}
else if (walkin == 'a' &&
gameboard[playery][playerx - 1] != '#' &&
gameboard[playery][playerx - 1] != '+' &&
gameboard[playery][playerx - 1] != '|' &&
gameboard[playery][playerx - 1] != '-') {
playerx--;
if (gameboard[playery][playerx - 1] == '#') {
pts -= 25;
}
if (gameboard[playery][playerx - 1] == 'P') {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery][playerx - 1] = '_';
}
}
else if (walkin == 'd' &&
gameboard[playery][playerx + 1] != '#' &&
gameboard[playery][playerx + 1] != '+' &&
gameboard[playery][playerx + 1] != '|' &&
gameboard[playery][playerx + 1] != '-') {
playerx++;
if (gameboard[playery][playerx + 1] == '#') {
pts -= 25;
}
if (gameboard[playery + 1][playerx] == 'P) {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery][playerx + 1] = '_';
}
}
if (walkin == 'a' || walkin == 's' || walkin == 'd' ||
walkin != 'a' || walkin != ' ' || walkin != 'd' ) {
for (ly = 0; ly = 202; ly++) {
for (lx = 1; lx = 25; lx++) {
gameboard[ly][lx] = 'L';
}
}
}
if (pts <= 0) {
system("clear");
renderLoss();
scanf("%c", replay);
if (replay == 'Y') {
gaming = 3;
}
if (replay == 'N') {
gaming = 5;
}
}
if (playery == 202) {
renderWin();
printf("");
printf("Congrats! You got a score of %d !", pts);
printf("");
scanf("%c", &replay);
if (replay == 'Y') {
gaming = 4;
}
if (replay == 'N') {
gaming = 5;
}
}
//player postion == 203y, then congrta screen
//ask player to set gaming to 4(replay) or none (exit program)
}
system("stty echo -raw");
return 0;
}
void render() {
int y,x,k;
system("clear");
printf("\033[01;33m");
printf("||POINTS: %d||\r\n", pts);
printf("\033[0m");
for (y = 0; y < 203; y++) {
for (x = 0; x < 26; x++) {
if (y == playery && x == playerx) {
printf("\033[0;32m");
printf("O");
printf("\033[0m");
}
else {
printf("\033[1;36m");
printf("%c", gameboard[y][x]);
printf("\033[0m");
}
}
printf("\r\n");
}
}
void titleRender() {
int y, x;
system("clear");
for (y = 0; y < 20; y++) {
for (x = 0; x < 59; x++) {
printf("\033[0;32m");
printf(" %c", titlescreen[y][x]);
printf("\033[0m");
}
printf("\r\n");
}
}
void renderLoss() {
int y, x;
system("clear");
for (y = 0; y < 26; y++) {
for (x = 0; x < 50; x++) {
printf("\033[0;31m");
printf(" %c", gameover[y][x]);
printf("\033[0m");
}
printf("\r\n");
}
}
void renderWin() {
int y, x;
system("clear");
for (y = 0; y < 20; y++) {
for (x = 0; x < 46; x++) {
printf("\033[0;33m");
printf(" %c", diffdiff);
printf("\033[0m");
}
printf("\r\n");
}
}
char quickchar(float delay) {
int flags;
char c;
usleep((int)(delay*1000000));
flags = fcntl(0, F_GETFL, 0);
fcntl(0, F_SETFL, flags | O_NONBLOCK);
c = getchar();
fcntl(0, F_SETFL, flags ^ O_NONBLOCK);
return c;
}

Function only returning return value it is not supposed to reach

I am working on a project for a programming class, where the goal is to verify a strength of a password based on different security levels. My problem is that with 2nd level, the:
Counter of numbers and special characters isn't working properly and isn't detecting numbers (it was working before I put it in its own function), but more importantly, the function only returns the value set in the very end. I have no idea what else to try.
int level2() {
while ((fgets(given_string, 100, stdin) != NULL)) {
for (int i = 0; given_string[i] != '\n'; i++) {
if (given_string[i] >= 'a' && given_string[i] <= 'z') {
lowerCaseLetterFound++;
} else if (given_string[i] >= 'A' && given_string[i] <= 'Z') {
upperCaseLetterFound++;
} else if (given_string[i] >= '0' && given_string[i] <= '9') {
numberFound++;
} else {
specialCharacterFound++;
}
}
}
printf("%d %d %d %d\n", lowerCaseLetterFound, upperCaseLetterFound, numberFound, specialCharacterFound);
if (param == 1 || param == 2) {
if (lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1) {
return 1;
} else {
return 0;
}
} else if (param == 3) {
if (((lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1) && numberFound >= 1) ||
((lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1) && specialCharacterFound >= 1)) {
return 1;
} else {
return 0;
}
} else if (param >= 4) {
if (lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1 && numberFound >= 1 &&
specialCharacterFound >= 1) {
return 1;
} else {
return 0;
}
}
return 0;
}
PS: This is my first time asking question here, and I am a programming newbie. Thanks for your help.
Update: Adding the whole code as I have it RN.
char given_string[100];
int lowerCaseLetterFound = 0;
int upperCaseLetterFound = 0;
int numberFound = 0;
int specialCharacterFound = 0;
int repeatedCharacter = 0;
int param;
int level;
int level1 () {
while ((fgets(given_string, 100, stdin) != NULL)) {
for (int i = 0; given_string[i] != '\n'; i++) {
if (given_string[i] >= 'a' && given_string[i] <= 'z') {
lowerCaseLetterFound++;
} else if (given_string[i] >= 'A' && given_string[i] <= 'Z') {
upperCaseLetterFound++;
}
}
}
if (lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1) {
return 1;
} else {
return 0;
}
}
int level2() {
while ((fgets(given_string, 100, stdin) != NULL)) {
for (int i = 0; given_string[i] != '\n'; i++) {
if (given_string[i] >= 'a' && given_string[i] <= 'z') {
lowerCaseLetterFound++;
} else if (given_string[i] >= 'A' && given_string[i] <= 'Z') {
upperCaseLetterFound++;
} else if (given_string[i] >= '0' && given_string[i] <= '9') {
numberFound++;
} else {
specialCharacterFound++;
}
}
}
printf("%d %d %d %d\n", lowerCaseLetterFound, upperCaseLetterFound, numberFound, specialCharacterFound);
if (param == 1 || param == 2) {
if (lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1) {
return 1;
} else {
return 0;
}
} else if (param == 3) {
if (((lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1) && numberFound >= 1) ||
((lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1) && specialCharacterFound >= 1)) {
return 1;
} else {
return 0;
}
} else if (param >= 4) {
if (lowerCaseLetterFound >= 1 && upperCaseLetterFound >= 1 && numberFound >= 1 &&
specialCharacterFound >= 1) {
return 1;
} else {
return 0;
}
}
return 0;
}
/*
int level3() {
while ((fgets(given_string, 100, stdin) != NULL)) {
for (int i = 0; given_string[i] != '\n'; i++) {
if (given_string[i] >= 'a' && given_string[i] <= 'z') {
lowerCaseLetterFound++;
} else if (given_string[i] >= 'A' && given_string[i] <= 'Z') {
upperCaseLetterFound++;
} else if (given_string[i] >= '0' && given_string[i] <= '9') {
numberFound++;
} else {
specialCharacterFound++;
}
}
}
}
*/
int main(int argc, const char *argv[]) {
//ukládám argumenty, prozatím pouze 2 ze 3
if (argc <= 1) {
printf("Not enough arguments provided. Please, provide LEVEL and PARAM arugments.\n");
} else if (argc >= 5) {
printf("Too many arguments provided.\n");
}
int level = atoi(argv[1]);
int param = atoi(argv[2]);
if (level <= 0 || level >= 5) {
printf("Level must be 1 through 4.\n");
}
if (param <= 0) {
printf("Parameter is not a full positive number.\n");
}
//vyhodnocování na základě zadaných parametrů - kontrola
//LEVEL = 1
if (level == 1) {
level1();
if (level1() == 1) {
printf("Password passed check 1.\n");
} else {
printf("Password did not pass check 1.\n");
}
}
if (level == 2) {
if (level1() == 1) {
if (level2() == 1) {
printf("Password did pass the check.\n");
}
} else {
printf("Password did not pass the check.\n");
}
if (level1() == 0) {
printf("Password did not pass the check.\n");
}
}
if (level == 3) {
}
}
Try to put your code in more than one function.
I think you can't print sth in your function. You should return just one thing you want to get from your function and then in another function, get input the first function's return.
It looks like the problem is that you’re re-defining your global variables in your main function. For example, when you do int param = atoi(argv[2]); in your main, param is scoped to your main. As soon as you leave your main function, you will be accessing the global param which has never been set.
You can either remove the variable type in your main so you are setting the global variables:
param = atoi(argv[2]);
Or get rid of the global variables and pass the ones created in main to any function that needs them.

Counting the occurrence of words in a file

My wordOccurrences don't work if you read a file. They can appear twice in the counting so it doesn't count correctly but if I input from stdin it counts correctly.
So I have to read in a file (-i input.txt) count the words and word occurrences in that file. Output the results in the specific file that is given with -o output.txt. If there is a -c it should ignore punctuation and convert to lowercase
MAIN
#include "count.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
//#include "wordOccurances.h"
#include "wordOccurrences.c"
int main(int argc, char **argv)
{
//Initialize variables
FILE *fi; // input file
FILE *fo =stdout; //output file
char buffer[1000];
char *input; //for manually entering string with -c
input = (char*)malloc(100 * sizeof(char));
char *name = "invalid";
int wordcount; // the number of words
char *ch; //a single character
ch = (char*)malloc(100000 * sizeof(char));
int c = 0, i, iFlag = 0, oFlag = 0, cFlag = 0;
char ptr1[50][100];
char *ptr;
if(argc == 1)
{
printf("Default settings\n");
}
else
{
for(i=1; i<argc;i++)
{
if(strcmp(argv[i], "-i")==0)
{
printf("input\n");
iFlag = 1;
fi = fopen(argv[++i],"r");
}
if(strcmp(argv[i], "-o")==0)
{
printf("output\n");
oFlag = 1;
fo = fopen(argv[++i],"w");
}
if(strcmp(argv[i], "-c")==0)
{
cFlag = 1;
}
}
}
if(iFlag ==1)
{
wordcount = countForFile(fi, wordcount);
fprintf(fo,"Word count is: %d \n", wordcount);
wordOccurencesForFile(fi, cFlag,fo);
}
else
{
printf("Enter text: ");
scanf(" %[^\n]s", input);
//Loop through input
int i = 0;
if(cFlag == 1)
{
int i =0;
for( i = 0;input[i]!='\0'; i++)
{
//find upperCase letters
if(input[i] >= 'A' && input[i] <= 'Z')
{
//overwrite to lowerCase
input[i] = tolower(input[i]);
//input[i] = input[i] +32;
}//end of if statement
//ignoring punctuation
if(input[i] == ',' || input[i] == '.' || input[i] == '!' || input[i] == '?' || input[i] == '"' || input[i] == ':' || input[i] ==';' || input[i] == '-')
{
input[i] = ' ';
}
} //end of for loop
}
wordcount = 0;
for(i = 0;input[i] != '\0'; i++)
{
if(input[i] == ' ' && input[i+1] != ' ')
wordcount++;
}// end of while loop
fprintf(fo,"WordCount is: %d\n", wordcount +1);
//count occurrences
wordOccurences(input, fo);
}
if(oFlag == 1)
{fclose(fo);}
}
wordOccurrences
/*
* C Program to Find the Frequency of Every Word in a
* given String
*/
#include <stdio.h>
#include <string.h>
#include "functions.h"
wordOccurences(char *input, FILE *output)
{
int count = 0, c = 0, i, j = 0, k, space = 0;
char str[100], p[50][100], str1[20], ptr1[50][100];
char *ptr;
// printf("Enter the string\n");
//scanf(" %[^\n]s", input);
printf("string length is %d\n", strlen(input));
for (i = 0;i<strlen(input);i++)
{
if ((input[i] == ' ')||(input[i] == ', ')||(input[i] == '.'))
{
space++;
}
}
for (i = 0, j = 0, k = 0;j < strlen(input);j++)
{
if ((input[j] == ' ')||(input[j] == 44)||(input[j] == 46))
{
p[i][k] = '\0';
i++;
k = 0;
}
else
p[i][k++] = input[j];
}
k = 0;
for (i = 0;i <= space;i++)
{
for (j = 0;j <= space;j++)
{
if (i == j)
{
strcpy(ptr1[k], p[i]);
k++;
count++;
break;
}
else
{
if (strcmp(ptr1[j], p[i]) != 0)
continue;
else
break;
}
}
}
for (i = 0;i < count;i++)
{
for (j = 0;j <= space;j++)
{
if (strcmp(ptr1[i], p[j]) == 0)
c++;
}
fprintf(output,"%s -> %d times\n", ptr1[i], c);
c = 0;
}
}
wordOccurencesForFile(FILE *fp, int cFlag, FILE *output)
{
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *str = (char*)malloc(fsize + 1);
fread(str, fsize, 1, fp);
fclose(fp);
str[fsize] = 0;
int count = 0, c = 0, i, j = 0, k, space = 0;
char p[1000][512], str1[512], ptr1[1000][512];
char *ptr;
if ( fp )
{
for (i = 0;i<strlen(str);i++)
{
if (cFlag == 1)
{
//ignoring punctuation
if(str[i] == ',' || str[i] == '.' || str[i] == '!'
|| str[i] == '?' || str[i] == '"' || str[i] == ':'
|| str[i] ==';' || str[i] == '-')
{
str[i] = ' ';
}
}
if ((str[i] == ' ')||(str[i] == ',')||(str[i] == '.'))
{
space++;
}
}
for (i = 0, j = 0, k = 0;j < strlen(str);j++)
{
if ((str[j] == ' ')||(str[j] == 44)||(str[j] == 46))
{
p[i][k] = '\0';
i++;
k = 0;
}
else
{
if (cFlag == 1)
{
//find upperCase letters
if(str[j] >= 'A' && str[j] <= 'Z')
{
//overwrite to lowerCase
str[j] = tolower(str[j]);
}//end of if statement
}
p[i][k++] = str[j];
}
}
k = 0;
for (i = 0;i <= space;i++)
{
for (j = 0;j <= space;j++)
{
if (i == j)
{
strcpy(ptr1[k], p[i]);
k++;
count++;
break;
}
else
{
if (strcmp(ptr1[j], p[i]) != 0)
continue;
else
break;
}
}
}
for (i = 0;i < count;i++)
{
for (j = 0;j <= space;j++)
{
if (strcmp(ptr1[i], p[j]) == 0)
c++;
}
fprintf(output,"%s %d \n", ptr1[i], c);
c = 0;
}
}
else
{
printf("Failed to open the file\n");
}
}

condition where two dots is typed it should print no?

First time posting here, having a problem with this code.
I want it to print no when there is more than 1 dot, for instance '2..5'.
Tried to put the following if statement:
if(num[i] == '..'){
printf("no \n);}
however with no success.
Im new to programming!
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *num = argv[1];
if (num[0] == '+' && strlen(num) >= 2 || num[0] == '-' && strlen(num) >= 2 || num[0] == '.' || (num[0] >= '0' && num[0] <= '9'))
{
for (int i = 1; i < strlen(num); i++) {
if (!(num[i] == '.' || (num[i] >= '0' && num[i] <= '9')) ) {
printf("no \n");
}
}
printf("yes \n");
} else {
printf("no \n");
}
}
}
Use this:
if(!(strcmp(num[i], "..")))
instead of
if(num[i] == '..')
Parsing numbers is not trivial. But the following works:
double parsenum(const char *num)
{
unsigned int i=0;
int neg= 1;
double result= 0.0;
int nFraction=1;
while (num[i]=='-' || num[i]=='+') {
neg= neg * (num[i]=='-'? -1 : 1);
i++;
}
while (num[i]) {
if (num[i]>='0' && num[i]<= '9') {
if (nFraction==1) {
result= result * 10 + (num[i]-'0');
}
else {
result= result + ((double)(num[i]-'0') / nFraction);
nFraction *= 10;
}
i++;
}
else if (num[i]=='.')
{
if (nFraction>1) {
printf("%s: no\n", num);
return 0.0;
}
nFraction *= 10;
i++;
}
else
{
printf("%s: no\n", num);
return 0.0;
}
}
result *= neg;
return result;
}
Test inputs:
printf("%f\n",parsenum("2..5"));
printf("%f\n",parsenum("-2.5"));
printf("%f\n",parsenum("--2.5"));
printf("%f\n",parsenum("2.5.6"));
printf("%f\n",parsenum("++2.555"));
printf("%f\n",parsenum("255.555"));

Resources