Printing leading zeros in a number in C [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm working on a project and I want my program to read a strictly 5 digits number with a leading zero.
How can I print the number with the leading zero included?
Plus: how can I provide that my program reads 5 digits including a zero as a leading number?

I assume you want to read in int variable. If so you can try the below solution.
#include<stdio.h>
void main()
{
int a;
scanf("%5d", &a);
printf("%05d",a);
}

The best way to have input under control is to read in a string and then parse/analyze the string as desired. If, for example, "exactly five digits" means: "exactly 5 digits (not less, not more), no other leading characters other than '0', and no negative numbers", then you could use function strtol, which tells you where number parsing has ended. Therefrom, you can derive how many digits the input actually has:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char line[50];
if (fgets(line,50,stdin)) {
if (isdigit((unsigned char)line[0])) {
char* endptr = line;
long number = strtol(line, &endptr, 10);
int nrOfDigitsRead = (int)(endptr - line);
if (nrOfDigitsRead != 5) {
printf ("invalid number of digits, i.e. %d digits (but should be 5).\n", nrOfDigitsRead);
} else {
printf("number: %05lu\n", number);
}
}
else {
printf ("input does not start with a digit.\n");
}
}
}

use printf family with '%05d" to print number with leading zeros. use sscanf to read this value (leading zeros are ignored).
Consult the following code:
int a = 25;
int b;
char buffer[6];
sprintf( buffer, "%05d", a );
printf( "buffer is <%s>\n", buffer );
sscanf( buffer, "%d", &b );
printf( "b is %d\n", b );
output is:
buffer is <00025>
b is 25

Related

Number in for loop doesn't increment [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I got the task to scan 10 numbers that will later on be converted into characters. The problem is that I don't get why there is an infinite loop if I don't enter 0. I got the task right with array but I am interested why does this happen in example bellow.
#include <stdio.h>
#include <stdlib.h>
int main() {
/**
* for the example enter numbers: 8 5 12 12 15 23 15 18 12 4 -> helloworld
*/
char n;
// message needs to be 10 numbers long.
for (int i = 1; i <= 10; i++){
// enter message in numbers.
scanf("%d", &n);
// check if it is 0. if it is, end the message.
if(n == 0) {
printf("\nEnd of the message!");
break;
// if number is not 0, add 64 to transform to char.
}else {
n = n + 64;
// print the char.
printf("%c ", n);
// print the i, that doesn't increment.
printf(" -> i:%d\n", i);
}
}
return 0;
}
You are using
char n;
...
scanf("%d", &n);
You cannot use %d with char. You should change n to an int or use %c for scanf and printf.
int n;
...
scanf("%d", &n);
OR
char n;
...
scanf("%c", &n);
You are using a char to read an int. The scanf fails and input remains in the buffer and so scanf keeps on reading the same value again and again resulting in an infinite loop.
So, declare n as an int.
It is a good practice to check the return value of scanf so that you will know if the input has been read properly.
The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure
The problem is with the scan!
scanf("%c", &n);
%d for ints, %c for chars, %s for strings, %f for floats!
scanf("%d", &n) reads an int into n. Since n is a char this results in the 3 bytes that appear after n being overwritten by the scanf. In your case the variable i was allocated within memory that overlaps those 3 bytes and so each call to scanf modifies the variable i resulting in a potentially infinite loop. Use %c to read in a character rather than %d.

How to read n numbers separated by space in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to read n integers from user during execution and the numbers are separated by spaces. It would be the best to be received as an array. For input 1 22 3 445 3, the result is, array[0]=1, array[1]=22 and so on. I have to do it in C. Can't use
scanf("%d %d %d", &var1, &var2, &var3);
because, I don't know how many such numbers would be inserted. The value of n would be read from user just before reading this data.
enum { MAX_NUMBERS = 1000000 }; // Choose appropriate upper bound
int n;
if (scanf("%d", &n) == 1 && n > 0 && n < MAX_NUMBERS)
{
int array[n];
for (int i = 0; i < n; i++)
{
if (scanf("%d", &array[i]) != 1)
…process error — terminate loop?…
}
…use array…
}
You can read multiple numbers with scanf() using a loop as shown. You've no idea whether they were all presented on a single line, or each was on its own line, or whether there were many blank lines between successive numbers (or any permutation of all these possibilities).
The scanf() family of functions basically do not care about newlines — it is hard to force them to do so. When you care about line-based input, use fgets() or POSIX function getline() to read a line and sscanf() — or other string parsing functions — to process the line.
I'm assuming support for C99 with VLA (variable length arrays). The principles are the same without that support — the mechanics are a little different (and there are multiple options for how to do it).
Use fgets() and then strtok() with atoi().
Take the numbers as a string.
Here is one way to do it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char numbers[100];
int myn[100];
printf("Give me numbers..\n");
fgets(numbers,100,stdin);
const char s[2] = " ";
char *token;
token = strtok(numbers, s);
int i=0;
myn[i]=atoi(token);
while( token != NULL )
{
i++;
printf( " %s\n", token );
token = strtok(NULL, s);
myn[i]=atoi(token);
}
printf("You gave me: ");
for (int j=0; j<i; j++){
printf ("%d, ", myn[j]);
}
return(0);
}
The above C program does exactly what you want. At the for loop, it prints to the screen the numbers you gave from keyboard. The "problem" would be much easier by using enter instead of spaces between the numbers.
Click on the links, to see very useful details about the functions used.

c - how to break scanf with no enter and no string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a project for school and in it, I need to get a four digit number and then continue immediately with no enter. For example: "Enter a number: 1424" and then it just continues, and you can't enter anymore numbers, aw well as Enter key pressing should not be needed.
I tried scanf("%4d",&num); but it waits for Enter key.
And one more restriction is... I can't use strings in this project, so all the solutions must be without strings.
The only way to organize input without Enter key press are functions getch and getche from conio.h header, that I suppose is not in C/C++ standard. So POSIX standard names are _getch and _getche.
With that functions you will read character - which are not strings if you process each char separately.
UPDATE:
My solution is:
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
char ch; // to store an input - single char
int number = 0; // to make number from inputs
printf("Enter a number: ");
int digits_cnt = 0;
while (digits_cnt < 4)
{
ch = _getche();
if (isdigit(ch))
{
number *= 10; // add an order to number
number += ch - '0'; // add a decimal digit to number
digits_cnt++; // count this digit to stop loop
}
}
// just to check result
printf("\nThe number %d was entered.\n", number);
return 0;
}
I assume that all 4 digits should become a number, but, perhaps, you need to do something else with them.
For reading 4 digits you probably want use char * fgets ( char * str, int num, FILE * stream ); that will do exactly what you are asking for. You should not use scanf for interactive input you can find why in this article
To the string part since you are typing input in ascii you are already working with strings(arrays of chars).

C Program Array more than 1 word [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This question is from HackerRank, I try to use %[^\n]s for a long word. But, the output keep on producing .0
How to replace %[^\n]s to something else for the string to receive the input ?
Here is the input :
12
4.0
is the best place to learn and practice coding!
Here is my output :
16
8.0
HackerRank .0
This is the expected output :
16
8.0
HackerRank is the best place to learn and practice coding!
This is my full code, as you can see, it does not recognize %[^\n]s. How to solve this problem? Thank you.
Full code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";
// Declare second niteger, double, and String variables.
int value1, sum1, value2;
double e = 2.0, sum2;
char t[30];
// Read and save an integer, double, and String to your variables.
scanf(" %d", &value1);
scanf("%d", &value2);
scanf("%[^\n]s", t); //** POINT OF INTEREST **
// Print the sum of both integer variables on a new line.
sum1 = value1 + i;
printf("%d\n", sum1);
// Print the sum of the double variables on a new line.
sum2 = d * e;
printf("%.1lf\n", sum2);
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
printf("%s %s", s, t);
return 0;
}
Considering your input-output examples, I amended your code like this:
char t[256]; // the string "is the best place to learn and practice coding!" MUST FIT!!!
...
scanf("%d", &value1);
scanf("%lf", &d); // NOT %d, %lf !!! &d or &e - I don't know - depends on you
scanf("\n%[^\n]", &t);
...
printf("%s%s", s, t); // you don't need a space, since your "s" already contains it.
Works fine for me.
UPD:
Now it actually works fine.
The reason your scanf() is failing to read the string is most likely that there's a newline character still in the stream that wasn't read off after you scanned the last number. "%[^\n]" tries to read a string, containing anything except a newline, and stops when an invalid character is reached; since the next character is a newline, there are no valid characters to read and it fails to assign the field. All you need to do to fix it is read the newline character before you scan the string.
Also, the %[ specifier does not need an s at the end -- it's a different conversion specifier from %s, not a modifier for it.
And finally, it's recommended that you specify the width for %[ or %s so that a long input string won't overrun the buffer you read the string into. The width should be the maximum number of characters to read before the null, so one less than your buffer size.
Using scanf(" %29[^\n]",t) will read off whitespace (including that newline) before scanning the string, and then scan a string with up to 29 non-newline characters (for a 30-char buffer).

How to scan integer values from a file separated by colon [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to get the integers values to be passed to a linked list from a text file.
The problem is that the text file is structured as columns and rows.
This is an example below regarding the text file:
5:0:3
4:1:2
3:1:1
4:2:2
3:3:1
How can I get these values? Noting that my program should notice the : and not only the EOF. I wrote a similar program but it can't take care of the colon. it only scans the integer values until the EOF.
You can use fgets() to read lines and then sscanf() to parse each line. If the lines, contain only 3 integers then it can be done as:
int i, j, k;
char str[256];
FILE *fp = fopen("filename", "r");
if(!fp) {
/* File opening error */
}
while(fgets(str, sizeof str, fp)) {
char *p = strchr(str, '\n');
if (p) *p = 0; // remove the trailing newline, if
if( sscanf(str, "%d:%d:%d", &i, &j, &k) == 3) {
printf("%d %d %d\n", i, j, k);
/* do processing with i, j & k */
}
else {
/* failure */
}
}
You can use fscanf as
fscanf(fp, "%d:%d:%d", &var1, &var2, &var3);
You can read in the entire line as a string using getline.
Then you can use the string function find() to find the :
After that you'll have saved in what position in the string the : was found, and you can convert the character that is one position behind the : into a integer using atoi(). That works for the first 2 numbers.
For the last number, you do the same thing but instead of : you look for a space.

Resources