Proper input method to take char string input in C

3652 views c
2

How would I best take input in a program that asks the user to enter a student name separated by a space and then the student score, EX:

zach 85

Because of the null terminator, will there be two enters that i will have to account for? I'm already using two scanfs in my program.

int main()
{
   const int row = 5;
   const int col = 10;
   int i;
   char names[row][col];
   int scores[row];
   int total;

   // Read names and scores from standard input into names and scores array  
   // Assume that each line has a first name and a score separated by a space
   // Assume that there are five such lines in the input
   // 10 points

   for(int i = 0; i<row; i++)
   {
       printf("Enter student name: \n");
       scanf("%s",&names);
       scanf("%s", &scores);
   }
   // Print the names and scores
   // The print out should look the same as the input source
   // 10 points

   for(int i = 0; i<row; i++)
   {
       printf( "%s %d \n", names[i]  /*, scores[i] */ );       
   }
}

answered question

1 Answer

6

first look scores and names are is defined as arrays so

   scanf("%s",&names[i]);
   scanf("%s", &scores[i]);

second scores are int so "%d" instead of "%s"

   scanf("%s",&names[i]);
   scanf("%d", &scores[i]);

posted this

Have an answer?

JD

Please login first before posting an answer.