I'm new to C, and I have an assignment where I get an input of n space separated integers, and q integers separated by new lines. I would like to save the n integers in an array a, and the q integers in another array m.
This is my code so far and it works as expected for m, but the elements in a are pretty random. How can I save the space separated integers into an array?
int main() {
// The code
int n, q;
int a[n];
int m[q];
scanf("%d %d", &n, &q);
for (int i=0; i<n; i++) {
scanf("%d", &a[i]);
}
for (int i=0; i<q; i++) {
scanf("%d", &m[i]);
}
// Troubleshooting
for (int i=0; i<n; i++) {
printf("%d ", a[i]);
}
printf("\n");
for (int i=0; i<q; i++) {
printf("%d\n", m[i]);
}
return 0;
}
For example when I input:
1 2 3 4 5 6
0
1
2
3
4
5
I get:
4 5 3 4 5 6
0
1
2
3
4
5
I'm not sure but when i run your code i get segmentation error because instead of:
int n, q;
int a[n];
int m[q];
scanf("%d %d", &n, &q);
You should first read n,q and then declare a[n],m[q] like this:
int n, q;
scanf("%d %d", &n, &q);
int a[n];
int m[q];
I tried running your code giving 6 6 for the first scanf so n=6,q=6
and after that as your example i gave input:
1 2 3 4 5 6
0
1
2
3
4
5
and it printed right.
Don't use scanf. scanf is notoriously hard to use, and it's particularly wrong for your situation because it will not distinguish between different types of whitespace (spaces versus newlines).
Instead, you should read input line-by-line using fgets and then parse each line using sscanf or strtok.
Related
I am trying to code a program that asks the user for the # of rows and columns and generates a 2d array (a matrix) corresponding to their input. I then ask for a second matrix (same dimensions), then I do some math on the 2 matrices. I'm stuck on how to use the scanf function to get the user-inputted matrix. According to the guidelines, the user input will be in the shape of the matrix itself, ex if it is a 2x2 matrix the user enters:
12 10 (then on the next line)
10 10
How do I use the scanf function appropriately to copy this matrix into the 2d array that I've created? I know that you can do scanf("%d %d %d", &int1, &int2, &int3), but I don't know if this will work for a user-determined matrix, since the length could be 2, 10, even a 100 (which is max length for this problem).
#include <stdio.h>
int main(void) {
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
/*User enters matrix in the form:
12 10
10 10
*/
printf("Enter Matrix A\n");
for(int i=0; i<sizeof(matrixA); i++){
for(int j=0; j<sizeof(matrixA[i]);i++){
scanf("%d ",&matrixA[i][j]);
}
}
//to see if scanf worked
for (int i = 0; i<sizeof(matrixA); i++) {
for(int j=0; j<sizeof(matrixA[i]);i++) {
matrixA[i][j] = '.';
printf("%c ",matrixA[i][j]);
}
printf("\n");
}
int matrixB[r][c];
printf("Enter Matrix B\n");
return 0;
}
You are right that
scanf( "%d %d %d", &int1, &int2, &int3 );
will only work if the number of parameters is fixed at compile-time. It cannot be changed at run-time.
Your idea of calling
scanf("%d ",&matrixA[i][j]);
in a loop instead is correct, in principle. However, you should not have a space character in the format string, as this will cause scanf to continue to read input from the input stream, and it will only return after it has encountered a non-whitespace character. This is usually not what you want.
Also, the line
for(int i=0; i<sizeof(matrixA); i++){
is wrong, because sizeof(matrixA) is the size of the array in bytes. Since you instead want to get the number of elements in the outer array, you could write sizeof matrixA / sizeof *matrixA instead. (The parentheses are only necessary when referring to types, not variables.) However, in this case, it would be easier to simply use r instead.
The line
for(int j=0; j<sizeof(matrixA[i]);i++){
is wrong. You probably intended to write j++ instead of i++.
Also, when printing variables of type int with printf, you should usually use %d instead of %c, because otherwise the value may be truncated if the value is higher than 127.
It is unclear what the line
matrixA[i][j] = '.';
is supposed to accomplish, as this will overwrite the previous input of scanf (assuming that you fix your loop as described above).
After fixing all of the issues mentioned above, your code should look like this:
#include <stdio.h>
int main(void)
{
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
printf("Enter Matrix A:\n");
for ( int i=0; i < r; i++ )
for( int j=0; j < c; j++ )
scanf( "%d", &matrixA[i][j] );
//to see if scanf worked
printf( "Input complete, the array contents are:\n" );
for ( int i=0; i < r; i++ )
{
for( int j=0; j < c; j++ )
printf( "%d ",matrixA[i][j] );
printf( "\n" );
}
return 0;
}
This program has the following behavior:
Please enter the number of rows : 4
Please enter the number of columns : 4
Enter Matrix A:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input complete, the array contents are:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
POSIX-specific answer
Well, you don't.
There are two ways to get that done:
Slice stdin into rows by the '\n' character n times; later slice every row in n columns by ' ' the whitespace. getline and strtok come in handy here.
The other approach is more efficient and as usual more complicated: rather than slicing into rows first, you iterative cut-off cols, counting them, and when count == n comes true, you expect '\n' to be there thus ending another line. I wouldn't suggest this approach.
So roughly your codes looks something like:
ssize_t nread;
for (sizet_t i = 0; i < n; i++) {
char *line = NULL;
if ((nread = getline(&line, &len, stream)) != -1) {
fprintf(stderr, "Bad format: %il-th line expected.", i + );
exit(EXIT_FAILURE);
}
char* token = strtok(line, " ");
for (size_t ii = 1 /* because you've already cut-off the first token */; i < n; ii++) {
token = strtok(NULL, " ");
}
}
Of course, you have to parse your char * tokens, but that is something I leave to you as an exercise. It also quite sloppy and does not do any sort of validation a production code is expected to do.
I am trying to scanf 5 numbers into an array in one command line prompt. I know how to store a value one by one into an array, but in this case I am trying to store 5 values in a line. I know how to hard code it when the limit is clear, but I want to code it based on a user inputted limit.
for example (hard code):
int arr[5];
scanf("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);
for (i = 0; i < 5; i++) {
printf(" %d", arr[i]);
}
would give me the values of arr[0] arr[1] arr[2] arr[3] arr[4].
BUT what if the size of aaa is defined by users, or defined by a macro that allows changes? How do you not hard code it?
#define MAX 10
int arr[MAX];
or
printf("what is the limit? : ");
scanf("%d", &limit);
int arr[limit];
I tried using a for loop but it doesn't work.
for(i=0;i<MAX; i++){
scanf("%d %d %d %d %d\n", &aaa[i]); //I want user to input 5 numbers in one line, but this format doesnt work.
}
To conclude/clarify my question.
I want user to input 5 numbers in one line. for example : 1 2 3 4 5 with a space in between. and I want it stored at arr[0] arr[1] arr[2] arr[3] arr[4]. Is there a way to not hard code this?
Help would be greatly appreciated! Thanks!
You want this:
#include <stdio.h>
int main()
{
int arr[5];
printf("Enter 5 numbers separated by space then press Enter\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < 5; i++) {
printf(" %d", arr[i]);
}
}
Execution:
Enter 5 numbers separated by space then press Enter
1 2 3 4 5
1 2 3 4 5
You need to read inputs in the loop as below.
for(i=0;i<MAX; i++) {
scanf("%d", &aaa[i]);
}
I currently am having a small trouble in my code, I am supposed to make a program that adds / sums all numbers inside of an array, while I have no problem in doing that, I currently have a problem with the part in which you are supposed to scan the numbers to be put in the array, here are the example of the input
3
5
1 2 3 4 5
8
1 2 3 4 5 6 7 8
9
1 2 3 4 5 6 7 8 9
What this means is that, the user inputs number "3" as it means to create 3 arrays, the number "5" afterward means to put 5 numbers inside of the array (1 2 3 4 5), after the user has inputted the numbers inside of an array, the user inputs "8" which means to make another array consisting of 8 numbers, and then putting numbers into the array again, and so on.
However I am having a problem in which after inputting all the numbers in the array that consists of 5 number, the program instead inputs 5 number into another array again (instead of asking the amount of numbers to be put inside of another array), so instead the number "8 1 2 3 4" gets inputted in another array, and I did not know which part I did wrong.
Here are my C code :
#include <stdio.h>
int main(){
int x, y;
int i;
int n;
int c=1;
int count=0;
int sum=0;
scanf("%d", &y); //this determines the amount of array to be inputted
scanf("%d", &x); //this determines the amount of numbers to be inputted inside of an array
int line[x];
for(int i=0; i<y; i++){
sum=0;
for(int i=0; i<x; i++){
scanf("%d", &line[i]); //scan number for the array
sum += line[i];
}
printf("Case #%d: %d\n", c, sum);//output of all sum
c++;
}
}
You need to read the size for each array - currently you only read it once.
e.g.:
int numLines;
scanf("%d", &numLines);
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
int line[numNumbers];
for(int i = 0; i < numNumbers; i++) {
scanf("%d", &line[i]);
}
}
Additionally you can avoid storing the individual numbers, since you're only interested in the sum, e.g.:
int sum = 0;
for(int i = 0; i < numNumbers; i++) {
int number;
scanf("%d", &number);
sum += number;
}
Also you could defer outputting the sums until all inputs have been processed, so it doesn't visually get interleaved into the input.
This would be a possible way to write that program: godbolt
#include <stdio.h>
int main() {
// get the number of arrays we need to read
int numLines;
scanf("%d", &numLines);
// The sums of each array
int sums[numLines];
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
// sum up all the numbers of the array
sums[lineIdx] = 0;
for(int i = 0; i < numNumbers; i++) {
int number;
scanf("%d", &number);
sums[lineIdx] += number;
}
}
// after all arrays have been entered,
// output the sums for each case:
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
printf("Case #%d: %d\n", lineIdx, sums[lineIdx]);
}
}
I input the values from scanf but when i print them, all the columns have the last row's values.
#include <stdio.h>
int main(){
int N, M;
int A[N][M];
int T[N][M];
int i,j;
printf("Insert number of rows and columns: ");
scanf("%d %d",&N,&M);
printf("\nInsert the matrix\n");
for(i=0; i<N; i++){
for(j=0; j<M; j++){
scanf("%d", &A[i][j]);
}
}
printf("\nInserted matrix:\n");
for(i=0; i<N; i++){
for(j=0; j<M; j++){
printf("%d ",A[i][j]);
}
printf("\n");
}
return 0;
}
I've tried checking if it's a index problem and printing each element with its coordinate but that seems to be fine, the problem must be somewhere in the scanf.
Input:
Insert number of rows and columns: 3 3
Insert the matrix
1 2 3
4 5 6
7 8 9
output:
Inserted matrix:
7 8 9
7 8 9
7 8 9
Turn on compiler warnings. Any decent compiler will warn you that in:
int N, M;
int A[N][M];
N and M are not initialized. Because they are not initialized, you do not know what int A[N][M]; will do. The array dimensions must be known when the declaration is reached.
You can move int A[N][M]; and int T[N][M]; to after the scanf that reads N and M.
Note that declaring arrays with variable lengths is not suitable for general code. It can be used for simple school assignments, but you should eventually progress to using malloc and other techniques. (Variable length arrays can also be used where the size is known to be within certain limits.)
the following proposed code:
cleanly compiles
performs the desired functionality
fails to check for errors when calling scanf()
and now, the proposed code:
#include <stdio.h>
int main( void )
{
int N, M;
printf("Insert number of rows and columns: ");
scanf("%d %d",&N,&M);
int A[N][M];
//int T[N][M];
int i,j;
printf("\nInsert the matrix\n");
for(i=0; i<N; i++)
{
for(j=0; j<M; j++)
{
scanf("%d", &A[i][j]);
}
}
printf("\nInserted matrix:\n");
for(i=0; i<N; i++)
{
for(j=0; j<M; j++)
{
printf("%d ",A[i][j]);
}
printf("\n");
}
return 0;
}
When run with the input:
3 3
1 2 3 4 5 6 7 8 9
The output is:
Insert number of rows and columns: 3 3
Insert the matrix
1 2 3 4 5 6 7 8 9
Inserted matrix:
1 2 3
4 5 6
7 8 9
The critical difference between the OPs posted code and this answer is the initialization of 'N' and 'M' before they are used in defining the size of the array: A[N][M]
I want to scan input and save it in a square 2d array.
The first two digits are saved in seperate variables, the first digit is a target number (irrelevant here), the second digit gets saved in variable m, i.e. m = 5 in this case. m is the number of rows/colums of the square matrix. The rest of the input should be saved in the array.
For this particular input, I get a segmentation-fault and random numbers are printed on the screen.
I used some printf statements to trace where things go wrong, and I noticed that the index i in the first loop jumped from 2 to 11 in one scenario, for other input it jumped to 33.
Thanks for your help! I hope I am not missing an obvious mistake.
Input: (each row is seperated by the previous by pressing enter.)
42 5
0 3 7 9 10
9 13 20 5 20
12 11 33 0 12
17 39 22 3 18
My code:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* arv[]){
int target; // for later processing, irrelevant here
int m; // m = #rows and #columns of array
int array[m][m];
scanf("%d %d", &target, &m);
int i, k;
for(i = 0; i < m; i++){
for(k = 0; k < m; k++){
scanf("%d", &(array[i][k])); // save value in array.
}
}
// the problem occurs before this point.
for(i = 0; i < m; i++){
for(k = 0; k < m; k++){
printf("%2d", array[i][k]); // print array.
}
printf("\n");
}
return 0;
}
You have not initialized the value of m before creating array[m][m]. Without initializing, the value of m can be anything.
Change:
int array[m][m];
scanf("%d %d", &target, &m);
to
scanf("%d %d", &target, &m);
int array[m][m];
This is the place where you messed up.
int m;
int array[m][m];
Here ,m is uninitialized and you are creating an array of m*m elements. You need m initialized before the declaration of the array. So move the array declaration after the scanf just after it so that m gets initialized before you declare the array.
#innclude <stdio.h>
int i, j;
int t[5][5];
i=0;
j=0;
while(i < 5)
{
j = 0;
while (j < 5)
{
scanf("%d", &(t[i][j++]));
}
i++;
}