Putting numbers inside array at once in C - c

I'm struggling finding an answer to this: I want to be able to control if a credit card number (let's say '378282246310005') fulfills certain criteria (f.e. does it start with the number 3).
I want to be able to type the whole number at once, and then check certain places in the number (f.e. every second). However, I only managed to put them in an array when typing them one after another, which is annoying:
int main()
{
int user_input[5];
int i;
for(i=0;i<5;i++)
{
printf("Credit Card Number Digit %d\n",i+1);
scanf("%d",(user_input+i));
}
if(user_input[0] == 5)
printf("MASTERCARD\n");
else
printf("INVALID\n");
return 0;
}

Just check each digit as it is entered and ignore any non-numeric input, e.g.
int main()
{
int user_input[16];
int digits = 0;
while (digits < 16)
{
int c = getchar(); // get character
if (c == EOF) break; // break on EOF
if (isdigit(x)) // if character is numeric
{ // convert it to int and append to user_input array
user_input[digits++] = c - '0';
} // (otherwise just ignore it)
}
if (digits > 0 && user_input[0] == 5)
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
return 0;
}

I would suggest scanning a string into an array of char and then access this array. The technique is included in this Wikipedia article, where the following code can be found.
#include <stdio.h>
int main()
{
char word[20];
if (scanf("%19s", word) == 1)
puts(word);
return 0;
}
The snipped reads a string in the array word, which can be accessed similar as in your question. Apparently, the maximum length of the string can be given as a parameter in the format string.

Related

Print output just beside the user input

According to the question, The user needs to enter the no of hours the vehicle is parked and the total charge for the hours should get printed beside it.
for example:
I created this simple program
#include<stdio.h>>
#include<math.h>
float calculateCharges(float hurs);
int main()
{
float hours;//total no of hours vehicle is parked
int i;
printf("%s%10s%10s", "Car", "Hours", "Charges");
for (i = 1; i <= 3; i++)
{
printf("\n%d\t", i);
scanf("%f", &hours);
printf("\t%f\n", calculateCharges(hours));
}
getch();
return 0;
}
float calculateCharges(float hurs)
{
float charges;
hurs = ceil(hurs);
if (hurs >= 24) charges = 10;
else
{
if (hurs <= 3) charges = 2;
else
{
hurs = hurs - 3;
charges = 2 + 0.5*hurs;
}
}
return charges;
}
But now every time I enter hours the charges are getting printed below it instead of beside it. As shown in the image:
Is there is a way to consume the newline after scanf? So that charges can be printed beside the scanf?
I have modified my code this way too, but it didn't make any difference.
printf("%s%10s%10s", "Car", "Hours", "Charges");
for (i = 1; i <= 3; i++)
{
printf("\n%d\t", i);
printf("\t%f\n",(scanf("%f", &hours),calculateCharges(hours)));
}
Let me know if the original question is required. I'm using Visual studio 2017 RC.
You can use something like this:
#include <iostream>
#include <windows.h>
//This will set the position of the cursor
void gotoXY(int x, int y) {
//Initialize the coordinates
COORD coord = {x, y};
//Set the position
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
return;
}
void getCursorXY(int &x, int&y) {
CONSOLE_SCREEN_BUFFER_INFO csbi;
if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
x = csbi.dwCursorPosition.X;
y = csbi.dwCursorPosition.Y;
}
}
I found it here.
As already written in one of the answers this solution is not platform independent.
But i guess there are similar solutions on other platforms and you can easy set the cursor on the position you want.
Example usage in your main:
for (i = 1; i <= 3; i++)
{
printf("\n%d\t", i);
scanf("%f", &hours);
gotoXY( 20, i + 1);
printf("\t%f\n", calculateCharges(hours));
}
Workarounds for scanf can be found here.
scanf_s always generates a new line upon enter and unfortunately other user input capturing platform independent functions I know of (getc & getchar) do so too. Anyway on Windows it could be done using _getch() from conio header.
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
int getIntFromUser()
{
char readCharacters[10];
int index = 0;
for (int currentChar = _getch(); currentChar != '\r'; currentChar = _getch())
{
if (currentChar == EOF)
{
// Some error that shouldn't occour in your simple homework program
}
if (index > 9)
{
// Another possible error case where you would start to write beyond 'readCharacters' array
}
// We might as well disallow anything but digits, enter & backspace (You don't need anything else, do you?)
if ((currentChar < '0' || currentChar > '9') && currentChar != '\b')
{
continue;
}
else if (currentChar == '\b')
{
if (index > 0)
{
// Delete last character
printf("\b \b");
readCharacters[index] = '\0';
--index;
}
}
else
{
printf("%c", currentChar);
readCharacters[index] = currentChar;
++index;
}
}
if (index == 0)
{
// User pressed enter without having entered a number, let's give him a zero then
return 0;
}
readCharacters[index] = '\0';
int retVal = atoi(readCharacters);
// Worth noting that the value of converted user given string shouldn't be greater than what a signed int can hold
return retVal;
}
int main(int argc, char* argv[])
{
// Unlike scanf_s this will not generate a new line on enter
printf("getIntFromUser() sample (enter a number)\n");
int someValue = getIntFromUser();
printf(" -- This will be printed on the same line. (someValue is %d)\n\n", someValue);
// scanf_s sample
int anotherValue;
printf("scanf_s() sample (Insert a number.)\n");
scanf_s("%d", &anotherValue);
printf("This will be printed on a new line\n\n");
printf("Press any key to exit.");
_getch();
return 0;
}
EDIT
I feel like the above would become less readable if I were to add a comment over every code line. Instead I'm going to paste some blocks of code 1 by 1.
But first about the _getch function: It waits for the user to type something into the console and then returns the user given char as an int. char implicitly converts to int, so you may compare the _getch result to a character as I did many times in getIntFromUser (e.g. if (currentChar == '\b') { ... }).
You should also know about the values a char can hold and what their values are as an int (check out http://en.cppreference.com/w/cpp/language/ascii).
Going by the table the char '0' would be value 48 as an int, which is what _getch would return if the user were to type a 0.
First declare an array/string of 10 elements. Hope you know about them already. In this case the array is basically a chain of 10 elements that are all of type char, which are also referred to as string.
char readCharacters[10];
An indexer for the string is required.
int index = 0;
Below we have the usual for loop that...
1st: creates a variable of type int and assigns the result of _getch to it.
2nd: will determine if the loop shall keep executing. In this case the loop will break when currentChar is not '\r', which is an escape sequence that represents enter as a character.
3rd: will execute stuff inside once and then update currentChar with a new _getch.
for (int currentChar = _getch(); currentChar != '\r'; currentChar = _getch())
Checks if the user input (retrieved via _getch) is smaller than '0' (value 48 as an int) and greater than '9' (value 57 as an int). If either of them is true it will additionally check if the value of currentChar is not '\b' (value 8 as an int), which is the escape sequence for a backslash.
When that additional check evaluated to true as well then the keyword continue is used. Meaning that the rest of the block in the loop is not executed and instead the loop will start at the top again by getting a new user input and evaluating if the loop is to be continued by checking if obtained currentChar was enter.
if ((currentChar < '0' || currentChar > '9') && currentChar != '\b')
{
continue;
}
NOTE: You might want to read the comments on the else statement before you read these.
When the above if statement was false we get to the next if-statement (actually else if) that we see below.
As mentioned above: '\b' is backslash and if this is the user given char as well as string/array index being greater than 0 we move one character backwards in the console by "printing" '\b' and then write an empty character in order to delete what was written at that place previously. That puts us back to the position we were before so we print another backslash. At this point you might wonder why not just go back to the previous line that scanf_s causes, but that won't work. We must also not forget to replace the last string character with a null terminator and then set the index back by 1.
else if (currentChar == '\b')
{
if (index > 0)
{
// Delete last character
printf("\b \b");
readCharacters[index] = '\0';
--index;
}
}
When we hit this point we know that currentChar is something between 48 and 57 ('0' and '9').
_getch told the program what the user's input was, but we cannot see it in the console unless we print it there. So let's do that.
Also append the user's given character to the string as well as incrementing the index by 1.
else
{
printf("%c", currentChar);
readCharacters[index] = currentChar;
++index;
}
Lastly we call the atoi function that will convert our string/array to an integer.
int retVal = atoi(readCharacters);

Print string shows symbols

I'm trying to write an ITOA (integer to array) function using pointers.
So this is what I got so far. I debugged and it works just fine. The thing is, the printing itself doesn't work. I'm adding two screenshots.
Would appreciate some help.
int num_length(int number)
{
int count = 0;
while (number > 0)
{
count++;
number /= 10;
}
return count;
}
void itoa(int number, char *strptr)
{
int number_len = num_length(number);
char *start = strptr;
strptr += number_len - 1;
while (strptr >= start)
{
*strptr = number % 10;
number /= 10;
strptr--;
}
}
void print_string(char *strptr)
{
while (*strptr != '\0')
{
printf("%c", *strptr);
strptr++;
}
}
void main(void)
{
int number;
char number_in_string[N] = { '\0' };
char *strptr = &(number_in_string[0]);
printf("Enter a number: ");
scanf_s("%d", &number);
itoa(number, strptr);
print_string(number_in_string);
getch();
}
If you're trying to get an array of numeric characters (as seems evident by your print_string(a) function), you'll need to adjust the values appropriately:
*strptr = number % 10 + '0';
As per your debugging output ('\x2', '\x5', '\x5') , you're correctly getting the individual digits of the number but those are binary values, not the character representations.
Turning the former into the latter involves adding '0' (0x30 if you're using ASCII, for example). C guarantees that the numeric values are contiguous so this is safe.
(a) ... which could, by the way, be replaced with a simple:
printf("%s", number_in_string);
in your main function.

Validation 2 digits minimum C language

My job is to make a password validator with:
No spaces allowed
1 Symbol
2 Digits
Minimum 6 characters
Maximum 10 characters
Just the above restrictions, so far I have done alone the 1, 2, 4, 5 and I can't solve the third requirement about 2 digits. I can only do so with 1 digit so how do I to do it with 2? I think regex doesn't work like C++ and C# in C. Here is my code:
#include <stdio.h>
#include <string.h>
int main(){
char pass[11];
int stop;
printf("Give password:\n");
scanf(" %[^\n]s",pass);
do{
if(strlen(pass)<6){
stop=0;
printf("Too short password.");
}
else if(strlen(pass)>10){
stop=0;
printf("Too long password.");
}
else if(strchr(pass, ' ')){
stop=0;
printf("No spaces.");
}
else if((strchr(pass, '$')==NULL && strchr(pass, '#')==NULL && strchr(pass, '#')==NULL && strchr(pass, '!')==NULL && strchr(pass, '%')==NULL && strchr(pass, '*')==NULL)){
stop=0;
printf("Must give at least one of $, #, #, !, %% or *.");
}
else{
stop=1;
printf("Your password is %s\n", pass);
}
}while(stop=0);
return 0;}
That's not really a regex. What you have there is basically a small program that checks its input for different conditions. So, in the same manner, to make sure you have 2 digits, let's create a function that counts the number of digits. Keep in mind that in ASCII the digits 0 to 9 are in a continuous block (this is very important, as you will see).
int countDigits(char *input) {
int digitCount = 0;
for (int i = 0; i < strlen(input); i++) // for every character
if (input[i] >= '0' && input[i] <= '9') // if it is a digit
digitCount++;
return digitCount;
}
I've written this function this way to introduce show some character manipulation techniques. It would have been better if the condition would be:
if (isdigit(input[i]))
for portability reasons. Note that the function isdigit is defined in the ctype.h header. There is still some room for improvement:
int countDigits(char *input) {
int digitCount = 0;
int noOfCharacters = strlen(input); // avoid strlen() being called
// for every iteration
for (int i = 0; i < strlen(input); i++) // for every character
digitCount += isdigit(input[i]);
return digitCount;
}
Now you need just to take this function and check if it returns 2 for the input you've got.
No reason for small-ish buffer. Test #5 cannot have been done properly with pass[11]
// char pass[11];
char pass[100];
Dangerous to use unlimited length input. Change to
scanf(" %99[^\n]",pass);
Count the digits
int cnt = 0;
for (i=0; pass[i]; i++) {
if (pass[i] >= '0' && pass[i] <= '9') cnt++;
}
if (cnt != 2) BadPsss();
RegEx search [^0-9] the input string and replace globally with nothing.
Verify the remaining string to be two characters long.

Using Array Integer

I'm new in C programming language.
I need to get every digit separately that user have entered.
Here is my code:
#include <stdio.h>
int main()
{
int n[100];
printf("Enter a number: ");
scanf("%d",&n);
printf("%d %d %d",n[1],n[2],n[3]);
return 0;
} //i know that my code is not assigning like i want.
and now for example user entered a number like 123, i want the output like 1 2 3, How can i assign every digit to n[i] ? Without using string to int or int to string like atoi? Here is what Im going to do: User will enter a number and the program will search from Matrix 100x100 in row or column. i think i need to get the every digit separately to search.
No need to go to character array. The lats digit of a number n can be computed using n%10. Then you can remove the last digit using n /= 10. So this cycle would print the digits in reverse order:
void print_rev_digits(int n) {
while (n) {
printf("%d\n", n%10);
n /= 10;
}
}
And using a stack you can print the digits in the correct order. You can also use recursion for this(which will use stack for you). I am deliberately not posting a complete solution.
In this case you should read the user input character by character:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main()
{
char input[100];
int n[100];
printf("Enter a number: ");
if (fgets(input, sizeof(input), stdin)) { // attempt to read a line
int i;
for (i = 0; input[i]; i++) { // for each entered character
if (input[i] >= '0' && input[i] <= '9') { // is a digit
n[i] = input[i] - '0';
printf("%d ", input[i] - '0');
}
else if (isspace(input[i])) // end of entered integer
break;
else {
printf(stderr, "Input is not a number\n");
return -1;
}
}
printf("\n");
} else {
fprintf(stderr, "User did not enter valid input.\n");
}
return 0;
}

How do I force user to input a positive integer?

Force user to input a positive integer and put user in a loop till they do.
So I want everything including characters not allowed just over > 0
I tried the following:
while (i < 0) do {
printf("please input a number that's positive");
scanf("%d", i);
}
For positive integer use the following code
int i;
do
{
printf("please input a number that's positive");
scanf("%d", &i);
}while (i < 0);
The c language provides no error checking for user input. The user is expected to enter the correct data type. For instance, if a user entered a character when an integer value was expected, the program may enter an infinite loop or abort abnormally.
Both of these while functions manage the numbers, the int k is the set integer which can only be set below 20, the first while loop makes a statement that calls for another scan if the number is greater than 20
and the second loop prints a k*k box.
Hope this helps.
int main ( )
{
int i, j,k;
printf("Please enter Box size:\n\n");
scanf("%d",&k);
while(k>20){
printf("Please enter a value below 20\n\n");
scanf("%d"),&k;
}
while(k<=20)
{
for (i = 0; i < k; i++)
{
printf("\n");
for (j = 0; j < k; j++)
{
printf("#");
}
}
return 0;
}
}
I would do this: declare char term and int wrong = 0.
do {
printf("Enter a number: ");
fflush(stdin);
if (scanf("%d%c", &n, &term) != 2 || term != '\n' || n <= 0) {
printf("Only positive numbers.\n");
wrong = 1;
}
else {
wrong = 0;
//do something here if correct;
}
} while (wrong);
The code above detects invalid input if the user entered a mixture of characters and numbers, or negative numbers (and zero).
However, it doesn't detect if the user entered trailing zeros in front followed by valid digits eg. 001or 00000738. If anyone else could figure this out, please share below. Thanks! :)
Here is another alternative of a function which takes in a char str[20] (of say, maybe 20 elements), analyses the string to check for positive integers, and returns a 0 or 1 accordingly. Lastly, convert that string to an integer using atoi().
int checkPositiveIntegers(char str[]) {
char *ptr = str;
if (*ptr == '-' || *ptr == '0') //checks for negative numbers or zero
return 1;
else {
do {
if (isdigit(*ptr) == 0) { //checks for non-digit at ptr location; isdigit() returns 0 if non-digit
return 1;
break;
}
ptr++;
} while (*ptr != '\0' && *ptr != '\n');
return 0; //returns 0 if positive integer
}
}
So the function only accepts positive numbers from 1 to 9,999,999,999,999,999,999 (up to 19 digits if char str[] holds 20 elements).
However, if you converted the string back to int n = atoi(str);, the maximum value it could reach would be 2,147,483,647 since n is declared as a signed integer. Play around with different datatypes for exploration.
Hope this helps! :)

Resources