scanf not reading second arguement - c

I have the following code which I am trying to run.
I want the scanf function to take in three different inputs, with the first two being integers between 0 and 30, and the third a string beginning with #.
The program compiles fine, but when I attempt to input the coordinates and the associated #symbol, I get a 0 in the y coordinate's place.
Does anyone know why this is happening or what I can do to fix it?
Below is the code
#include <stdio.h>
int main(){
int grid[30][30];
int i, j;
for(i=0; i<30;i++){
for(j=0; j<30;j++){
grid[i][j]='.';
}
}
int x_coord;
int y_coord;
char type[2];
scanf("%d %d %s",&x_coord,&y_coord,type);
/*added extra whitespace*/
printf("%i %i %s",x_coord,y_coord,type);
printf("\n");
grid[x_coord][y_coord]=type[1];
//end outer loop
for(i=0; i<30;i++){
for(j=0; j<30;j++){
printf("%c",grid[i][j]);
}
printf("\n");
}
return(0);
}//end main

As you declared char type[2]; and you are first entering # and then new character suppose X so in type it will go like this
type[0] = #
type [1]='\0'
so you should declare char type[3]; this way
so that
type[0] = #
type [1]='X'
type [2]='\0'
it will stored this way and you can get X by accessing type [1]

Assuming you are entrering #X for the string, where X is some single character, scanf is going to attempt to fill type with '#' 'X' and '\0' (null byte added by scanf to mark the end of the string)
That's 3 bytes being stored in array that is only big enough for two.

Related

C for loop goes on forever and I think I wrote the program wrong

This is my homework assignment:
And this is my code:
#include <stdio.h>
int main() {
char v[2] = {'A', 'I'};
char c[3] = {'n', 's', 't'};
int i;
for (i = 0; i < c[i]; i++) {
printf("%d %d %d %d %d %d", c[6]);
for (i = 0; i < v[i]; i++) {
printf("%d %d", v[2]);
}
}
return 0;
}
It seems to go on forever and I don't know what to do. Keep in mind that I am new to C, so I tried my best.
it seems you want to write the first letter of v[] combined with each letter of c[]
Then write the second letter of v[] combined with each letter of c[]
This hints the first/outer loop would be stepping through the array v[]
This hints the second/inner loop would be stepping through the array c[]
This hints within the inner loop would be outputting the current letter from v[] followed by the current letter from c[] followed by a space.
remembering that / (divide) has a higher precedence than < see C precedence table:
(remembering that sizeof() returns the number of characters in an object so obtaining the number of entries in an array is the total size of the array, in characters, divided by the number of characters in the first element of the array)
how to step through array v[]:
for( int i=0; i < sizeof(v) / sizeof(v[0]); i++ )
how to step though array c[]:
for( int j=0; j < sizeof(c) / sizeof(c[0]); j++ )
within the inner loop to print the current entry in v[] followed by the current entry in c[] followed by a space:
printf( "%c%c ", v[i], c[j] )
of course the above call to printf() places everything into the stdout I/O stream buffer and you actually want to display the output on the terminal, so after the nested loops exit, suggest:
printf( "\n" );
which is one way to flush the stdout buffer to the terminal.
Of course, all the above needs to be in a main() function
Of course, to use printf() need to include the header file: stdio.h
If you need clarification on any of the details, post a comment to this answer.
regarding:
printf("%d %d %d %d %d %d", c[6]);
the number of `output format conversion specifiers must match the number of values to be output. In the current statement, 6 output specifiers does not match one value to be output.
Also, the c[] array only has 3 elements and C is zero based, so the only valid indexes are 0..2, not 6. Accessing index 6 results in accessing beyond the end of the array, which results in undefined behavior.

Is it possible to make some loop which scans always one number and one string more than once? (Part of my homework)

so in my CS course we have to make a calculator which reads input and then calculates the result after the = sign has been read.
Input always consists of one number followed by operator.
I'm now struggling with the way of scanning the input. I want to use some loop which would always store it like:
scanf("%lf %s ", &in, c);
Note: the calculator goes one operation after other. Thus in example below the plus sign works only for 20 and 4, and only then the result takes the division sign and gets divided by 8. Then the new result gets negated by 'neg' string.
E.g.: Input: 20 + 4 / 8 neg =
Output: Result: -3
This is how I tried to solve it. My intention was to make the loop store each number into a new "box" of array, and then to store each string into the new "line" of char array. The 4 in op array is meant to set the max length of the string, because i know that the longest string that can occur is "sqrt".
I see that the '\n' in the condition of for is probably useless but can't figure out how to do it...
I'm thinking about using either for, or a while loop.
int main(){
double in[10];
char op[5][4];
for(int i=0; i<5;i++){
scanf("%lf %s ", &in[i], op[i][4]);
}
printf("%.3f %s", in[0], op[0][0]);
return 0;
}
//just a "skeleton" of the code. There's more to it, but here I submitted just the part that I'm struggling with.
For example if I run this code, I want to write a few numbers followed by operator into the input.
I expect it to print the first number and string (just to check whether the loop works).
But actually it does absolutely nothing and just gives me some large negative number as a return.
From the man page of scanf
int scanf(const char *format, ...);
as you can see first argument is of const char * type i.e you need to provide valid address.
With this
char op[5][4]; /* 5 char array, in each char array you can have 4 char's
* i.e op[row][0] to op[row][3]. There is no op[i][4]
*/
you can have
for(int i=0; i<5;i++){
scanf("%s",op[i]); /* op[i] itself address, so don't need & */
}
or
for(int i=0; i<5;i++){
for(int j=0; j<4; j++) {
scanf(" %c", &op[i][j]); /* storing char by char */
}
}
Also while printing here use %c as op[0][0] is of char type.
printf("%.3f %c", in[0], op[0][0]);
In a scanf format string, %s indicates you want to read a string, meaning it needs the address of where to put that string. You are passing op[i][4] for it, which is a char.

Extra Character Whenever I Print Out at An Output

I am trying to do a FLAMES program as an assignment and since I can't exactly post my whole code here, I will type in the part of the code that seems to be causing me errors since whenever I print out something, there are unexpected extra characters going with the output.
I used a similar code as this one:
int main(){
char chari[100], temp[100];
int i, c;
printf("Enter a name: \n");
scanf(" %[^\n]s", chari);
for (i=1; chari[i]!='\0'; i++)
{
printf("%i\n", i);
}
c = i;
for (i=0; i<c; i++)
{
printf("%i < %i\n", i, c);
temp[i] = chari[i];
}
printf("%s \n", temp);
return 0;
}
I've been tweaking the codes for hours now but I still can't seem to find the problem. I'm also counting the number of letters in the string so I can stop some part of my program later on.
Input: cool
Expected output: cool
Actual Output: cool(<-t
You forgot to copy the terminating null character.
After your first loop c = i; holds the index of the 0 byte.
In the second loop you run until i < c, i.e. you do not copy that 0 byte
Without terminating nul your string is as long as another random 0 byte is found in memory.
Within a function only static variables are initialized. Hence your temp array hold indetermined values and you cannot rely to get a 0 character where you need it.
You need to copy 1 more byte.

call text file with words and numbers into arrays in a single function prototype

I aimed to read text file such as
File:
1 2 93 35 I_have_no_idea
2 4 5 45 I_dont_care
I want to read in into arrays (5 arrays)
Code:
int read_data(int id[], double year[], double earning[], double budget[], char name[]){
int i, nmovies;
int ch;
if ((ch = getchar())==EOF){
return -1;
}
for (i=0; scanf("%d", id+i)==1 && scanf("%d", id+i) != EOF ; i++){
while(fscanf(
scanf( "%lf %lf %lf %s\n", year+i, earning+i, budget+i, name+i);
}
nmovies = i;
return nmovies;
}
But it just giving me single id value.
What is wrong and how this should be changed?
you should make a class of this, not a method. (a dictionary is also an option, but i wouldnt recommend it)
after that you should make a new instance of the class for every line in the text file. you can put those in a list or an array of the class
(FYI if you want to keep using it like this, then you should at least make the char name[] a string name[])
edit:
if this is in C then you can discard the above, because then you dont have classes. If its c++ then do use it as above in a class
in the condition of your for loop, scanf("%d", id+i)==1 && scanf("%d", id+i) != EOF, you call scanf twice. Since i has not yet been incremented, the second call will overwrite the result of the first call.
Further, scanf returns the number of fields successfully converted and assigned. It does not return EOF.

Reading data from a textfile using the command line into an array in C confusion

I'm looking to read the following file into a 2D array using C.
AAAAAAAAAA
YYYYYYYYYY
AAAABAAAAA
XXXXXXXXXX
The files name is input4-10 and I'm using the following command line to run the program:
./a.out 4 10 <input4-10
Here is the program:
#include <stdio.h>
#include <stdlib.h>
int N=0;
int M=0;
int main(int argc, char **argv)
{
if (argc!=3)
{
printf("Usage : pairwise numberOfSequences lengthOfSequences\n eg. pairwise 10000 50\n");
exit(0);
}
sscanf(argv[1],"%d",&N);
sscanf(argv[2],"%d",&M);
char strings[N][M];
int i,j;
for (i=0; i<N; i++)
{
scanf("%s\n",strings[i]);
}
printf("[] %s\n",strings[0]);
printf("[] %s\n",strings[1]);
printf("[] %s\n",strings[2]);
printf("[] %s\n",strings[3]);
}
But when I print this out, I keep getting:
[] AAAAAAAAAAYYYYYYYYYYAAAABAAAAAXXXXXXXXXX
[] YYYYYYYYYYAAAABAAAAAXXXXXXXXXX
[] AAAABAAAAAXXXXXXXXXX
[] XXXXXXXXXX
How is this even happening?? In the following line scanf("%s\n",strings[i]); what exactly is being put into strings[i]? The whole fine? I'm so confused I literally want to have:
Strings:
AAAAAAAAAA
YYYYYYYYYY
AAAABAAAAA
XXXXXXXXXX
As a 2D array i.e:
strings = [A][A][A][A][A][A][A][A][A][A]
[Y][Y][Y][Y][Y][Y][Y][Y][Y][Y]
[A][A][A][A][B][A][A][A][A][A]
[X][X][X][X][X][X][X][X][X][X]
etc. Any help would really be awesome.
Your strings do not allow for the 0 terminator. Try this:
char strings[N][M+1];
What is happening is that the 0 terminator overflows into the next string, which is then overwritten by the next string data, etc. So printing each string prints the higher array elements too as the only 0 terminator is after the end of the last string, possibly over j which is unused.
Having said that, your code is still dangerous as it does not check whether the user entered a string that is longer than he specified. You can protect against string entry being too long by creating a format spec restricting the input length on the fly (the * length specifier as used by printf did not work in my compiler). The first two % signs are to create a single text %, the third % is part of %d which uses your string length M. There are two \ chars so that the text "\n" goes verbatim in the string, not as a newline.
char spec[20];
sprintf (spec, "%%%ds\\n", M); // create format spec as say "%10s\n"
//printf ("Spec %s\n", spec); // print the spec just so you can see
for (i=0; i<N; i++)
scanf(spec, strings[i]);

Resources