I want to read a file containing numbers in two columns.
1 2
3 4
5 6
7 8
I want to place the numbers in the first column into one array, and the ones in the second column into another array. Both of these arrays will always have the same amount of elements. The maximum number of elements permitted in this program is 100.
Here's what I have so far. This just reads in the elements as regular int and prints them out.
while (!feof (filereader))
{
printf ("%d %d\n",col_one,col_two);
fscanf (filereader, "%d %d", &col_one, &col_two);
}
So how do I place the numbers in the first column from the file into one array and the numbers in the second column into an array?
int array1[100];
int array2[100];
int i, size = 0;
while (size<100 && fscanf (filereader, " %d %d", &array1[size], &array2[size])==2)
{
size++;
}
for (i=0; i<size; i++) {
printf("array1[%d] = %d, array2[%d] = %d\n",
i, array1[i], i, array2[i]);
}
add space at the beginning of the format specifier of scanf " %d %d" this will avoid the problem of newlines in your file
Since you've got a maximum size, it's pretty easy. Just define the arrays like so:
int firstArray[100];
int secondArray[100];
int size = 0;
Then do your loop, incrementing the index for each line:
while (!feof (filereader))
{
fscanf (filereader, "%d %d", &col_one, &col_two);
firstArray[size] = col_one;
secondArray[size] = col_two;
size++;
}
Maybe also think about making sure size < 100 in case the file is too long.
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 need to get the user to input 6 numbers and I store those in an array called winningNum[]. Then I have to read in a file that has a bunch of users firstName lastName and the numbers they have guessed. I need to compare these two arrays and only print out the first and last name of the users from the file that got a minimum of three numbers matched.
This is the struct of for the input file users
typedef struct
{
char firstName [20];
char lastName [20];
int numbers[6];
}KBLottoPlayer;
Getting the winning numbers from the user
int getNum()
{
int winningNum[6];
int i;
printf("Please enter the six nunbers between 1-53:\n");
scanf("%d %d %d %d %d %d", &winningNum[0], &winningNum[1],
&winningNum[2] ,&winningNum[3], &winningNum[4], &winningNum[5] );
}
This is where I am reading in the file and putting it into the struct array
KBLottoPlayer* readArray()
{
int i,size;
FILE *in = fopen("KnightsBall.in","r");
fscanf(in,"%d",&size);
KBLottoPlayer* temp;
temp =(KBLottoPlayer*)malloc(sizeof(KBLottoPlayer)*size);
if((in = fopen("KnightsBall.in", "r")) != NULL )
{
char buffer[100];
fgets(buffer, 5, in);
for(i=0;i<size;i++)
{
fscanf(in," %s %s ", temp[i].firstName, temp[i].lastName);
fscanf(in,"%d %d %d %d %d %d ", &temp[i].numbers[0],
&temp[i].numbers[1], &temp[i].numbers[2], &temp[i].numbers[3],
&temp[i].numbers[4], &temp[i].numbers[5]);
}
}
else
{
printf("File is Not Exist.\n");
}
return temp;
}
I essentially need to only store the first and last name of the users that got 3 4 5 6 of the winning numbers correct.
I will admit that you only need hints to go past a problem.
Unrelated, but you never test your input functions. Beware a single incorrect line will give undefined results and you will not even know where the problem is. Remember: never trust what comes from the outside.
Back to your problem. A simple way is to use 2 nested loops, one on the winning numbers and one on the guessed ones just counting the matches: if the total number of matches is at least 3, you keep the record, else you reject it. You can even do that when reading the file (here in pseudo-code):
int recnum = 0; // next record to store
for (int i=0; i<size; i++) { // loop over the input file
read the line into temp[recnum]
int count = 0; // number of correct guesses
for (int j=0; j<6; j++) { // loop over the winning numbers
for (int k=0; k<6; k++) { // loop over the guessed numbers
if winning[j] == guessed[k] {
count++;
}
}
}
if (count >= 3) recnum++; // only keep if at least 3 correct guesses
}
int main()
{
int i, Quant, *Qsize1[4];
char *size1[4], size[5];
for(i=0; i<3; i++)
{
printf("Select Size : (S, M, L, XL) ");
scanf("%s",size);
size1[i]=size;
printf("How much quantity for this size? : ");
scanf("%d",Quant);
Qsize1[i]=Quant;
}
for(i=0; i<3; i++)
{
printf("\nSize %s : %d",size1[i], Qsize1[i]);
}
return 0;
}
example of print that i want is = Size L : 25
but when i print the it will print the last size i enter.
also the quantity of that size is wrong.
All the sizes are the same when you print them because you're reading all of them to the same character array named size. Each iteration overrides the previous size, and then you end up with size1[0], size1[1], size1[2] all point to the last size.
Quantity is wrong because you should pass scanf the address of the integer: scanf("%d", &Quant);
Also, as mentioned in the comments, you should fix how you read size itself. See this question about how to do it properly.
Sorry if my English is poor. What I'm trying to do is get the scanf to be entered on the same line. For example Enter value: 1 6 8 9 4 1 2 8 5 and it to be separated by a space. Then the numbers to be stored in an array. This is my code:
#include <stdio.h>
int main(void)
{
int a[10], smallest, i;
printf("Random\n");
for (i = 0; i < 9; i++)
scanf("%d", &a[i]);
smallest = a[0];
for (i = 0; i < 9; i++)
{
if (a[i] < smallest)
{
smallest = a[i];
}
}
printf("\nSmallest Element : %d\n", smallest);
}
Thanks for any help!
Edit: I'm trying to make the user enter 9 numbers which are stored in the array using scanf but when entering the numbers the scanf goes to a new line for example:
> 5
> 6 and so on what I want is for them to enter the number numbers on the same line with a space in between like this Enter value: 1 6 8 9 4 1 2 8 5
Scanf will await for a complete line. I suggest you take your input as a string then use strtok to extract the values and then assign.
Edit: You could use the scanf like that:
scanf( "%d %d ...", &a[0], &a[1]...); //as many values you're to assign
However, I prefer the method I proposed initially. Keep in mind scanf is derived from "scan formatted". You'll also have to handle the result from the scanf, it returns the number of values successfully filled.
you can scanf all numbers in one statement: scanf("%d %d %d %d %d %d %d %d %d %d", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7], &a[8], &a[9]);
This will let you scan 10 numbers with spaces between them, without the need to hit enter every time
note that I scanned 10 ints, because your array can store 10 ints, while your loop only scans 9... (to fix it, change i < 9 to i < 10 as Sourav Ghosh suggested)
For my task I have to print numbers to the screen and decode them into their specific letters. I'm using only the letters a-l in this code just to keep it simple so I can understand it.
The problem I'm having is that when I, for example, put in the number 0 which corresponds to the first entry to the array which is a, it will take out a and print b-l.
How do I make it so if I put in the number 0, the code will print only a to the screen?
#include <stdio.h>
int main()
{
char code[] = "abcdefghijkl";
int i, j, k;
printf("how many letters does your code contain?: ");
scanf("%d", &j);
for(i=0; i<j; ++i){
printf("enter a number between 0 and 11\n");
scanf("%d", &k);
printf("%s\n", &code[k]);
}
}
You print only the character at that location, so change
printf("%s\n", &code[k]);
to
printf("%c\n", code[k]);
You should also check that the value you read into k is >= 0 && < 11 , otherwise you'll access the array outside its bounds.
%s format specifier is used for printing strings, you need to use %c specifier which prints a character to the screen.
printf("%c\n", code[k]); instead of printf("%s\n", &code[k]);