简体   繁体   中英

Reading ints from standard input and saving them - C

The first line of input contains one integer. Each input is then followed by a line containing two integers, each no larger than 1 000 000. The first integer n is the size of the vector and the second integer m is the number of lines register information from. Each of the following lines contains two integers x and y indicating that. Any two integers in a line are separated by one white space. The lines contain no othercharacters, aside from the finishing new line

so I chose the x as the position in the vector. x is stored in num1 in the my_struct structure and y is stored in num2

typedef struct my_struct{
  int num1;
  int num2;
  bool my_bool;
} my_struct;


int main(){
   int testCase, sizeVector, numLines, num1_in, num2_in, linesScanned = 0;
   scanf("%d\n %d %d", &testCase, &sizeVector, &numLines);

   my_struct my_vector[sizeVector+1];

   my_vector[0].num1 = testCase;
   my_vector[0].num2 = 0;
   my_vector[0].my_bool = false;

   while (linesScanned < numLines) {
      scanf("%d %d\n ", &num1_in, &num2_in);
      my_vector[num1].num1 = num1_in;
      my_vector[num1].num2 = num2_in;
      my_vector[num1].my_bool = false;
      linesScanned++;

   }}

input example:

1
3 2
1 2
2 3

my problem is that the first scanf works well, but the on on the loop doesn't. It doesn't save the values as it should

Change the second scanf() :

scanf("%d %d\n ", &num1_in, &num2_in);

by

scanf(" %d %d", &num1_in, &num2_in);

In fact in your second scanf() you do not catch the new line before starting reading integers. The new line is entered in your input but it is not catched neither in the first scanf() nor in your second scanf()

Adding space at the beginning of the string format in your second scanf() will catch any white space (spaces, tabulation , new lines...)

Change your code to get rid of the \\n in your scanf functions. In fact you can get rid of the spaces too. When using %d all whitespace in the input is ignored.

You also don't appear to be incrementing your array index.

你的第二个scanf应该是:

scanf(" %d %d", &num1_in, &num2_in);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM