How to read n numbers separated by space 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 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.

Related

How can I fix Address boundary error in C? [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 3 years ago.
Improve this question
I'm new to C,and want to write a simple program that takes a user input and prints it out a specific amount of times back to them.
#include <stdio.h>
#include <stdlib.h>
int main() {
char* str[100];
int *p = malloc(sizeof(int) * 10);
int amount;
*p = amount;
int i;
printf("\nType anything!\n");
scanf("%s", str);
printf("\nHow many times?\n");
scanf("%d", amount);
for (i=0; i<=amount; i++) {
printf("%s", str);
}
return 0;
}
It works fine,until after pressing entering the amount of times,when the program crashes with the Fish shell saying "fish: “./a.out” terminated by signal SIGSEGV (Address boundary error)".
Address boundary error tells me that maybe I haven't allocated memory for something,but how would I go about doing that? I've tried using malloc with a pointer pointed at amount but it doesnt seemed to have solved anything.
It's remarkable how many issues there are in such a short chunk of code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[100];
int amount;
printf("\nType any word!\n");
if (scanf("%99s", str) != 1)
{
fprintf(stderr, "Failed to read a string\n");
return(EXIT_FAILURE);
}
printf("\nHow many times?\n");
if (scanf("%d", &amount) != 1)
{
fprintf(stderr, "Failed to read an integer\n");
return(EXIT_FAILURE);
}
for (int i = 0; i < amount; i++)
{
printf("%s\n", str);
}
return 0;
}
The signature of main() is a full prototype.
The type of str is corrected (or, at least, changed and made usable).
The code related to p and malloc() is not needed.
The variable i is moved into the for loop (assumes a C99 or later compiler; if not available, what you had was OK).
Change "anything" to "any word" because %s skips white space and then reads non-spaces up to the next white space.
Limit the amount of input to prevent overflows.
Report if there's a problem reading the string and exit.
Fix the scanf() to pass &amount (key change).
Check for success reading amount and report failure and exit.
Define i in the loop control (C99).
If the user requests one copy, only print one copy (change <= to < — that's an idiomatic C loop now).
Output newline after each word. There are other ways to present the data, including the one chosen originally, but you should at least end the output with a newline.

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.

Printing leading zeros in a number 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 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

scanf format string not recognized [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 4 years ago.
Improve this question
I' ve inserted the followings input for the follow program:
a b c d e
After the e letter I've pressed Enter, but the program blocks on scanf for i equal to 3.
Seems that scanf is not able to fetch other character from stdin.
Thanks in advance for your help.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[5];
for (int i = 0; i < 5; i++)
{
scanf("%c ", a + i);
printf("i = %d a[%d] = %c \n", i, i, a[i]);
}
int i = 0;
while( i < 5 )
{
printf("%c ", a[i]);
i++;
}
return 0;
}
It doesn't block when i == 3 -- it completes that iteration -- it blocks when i == 4.
That's because of the space after the %c in the scanf format -- a space causes scanf to read input and skip whitespace up until it finds a non-whitespace character. That non-whitespace character will then be left in the FILE input buffer as the next character to be read. So in the 5th iteration of the loop (i == 4), it reads the e then reads whitespace looking for non-whitespace. So the newline is skipped over (it's whitespace) and it starts (trying to) read the next line which blocks.
Once you provide the next line (assuming its not empty/all whitespace), it will get a non-whitespace character and scanf will return.
Using scanf to fetch a single character at a time from stdin is not a good idea. If the user types more than one character, you can overflow the buffer as there is no room for the null character. This also leaves excess characters in stdin.
Another idea is to use a special format string flag to fetch 5 characters at once, and then print them or do whatever you want with them.
You can use the flag "%5c", where 5 is any integer number, that reads, scan exactly 5 characters.
Here is the modified version of your code
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[5];
scanf("%5c", a);
int i = 0;
while( i < 5 )
{
printf("%c ", a[i]);
i++;
}
return 0;
}
Now there is no blocking.

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).

Resources