简体   繁体   中英

Why does my program exit after taking a input

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int n;
    char name[100];
    int number;
    printf("Enter the value of n\n");
    scanf("%d",&n);
    printf("Enter %d values\n",n);
    for(int i=0;i<n;i++)
    {
      scanf("%[^\n]s",&name);
    }       
  }

Whenever i am entering the value of n it just prints (Enter n values) and exit the program. For loop never runs. I dont get it coz it ran successfully for the first time but after that it just exits the program.

EDIT: There were some answers that it isnt printing anything I dont want it to print just to take input n times it is not doing that.

My aim is to I am trying to take n as input and then want to take strings of names (like harry, robin etc) n number of times as input.

Your code is a little incomplete. And there are a few errors here: scanf ("%[^\\n]s",&name)Do this and everything will be fine:

#include<stdio.h>
#include <string.h> 
#include <math.h> 
#include <stdlib.h>

int main(void)
{
int n;
char name[100];
int number;
printf("Enter the value of n\n");
scanf(" %d",&n);
printf("Enter %d values\n",n);
for(int i=0;i<n;i++) 
{ 
    scanf(" %99[^\n]",name);
    printf("%s\n",name);
}
    return 0;
}

scanf is particularly unsuited for user input.

You probably want this:

int main() {
  int n;
  char name[100];
  int number;
  printf("Enter the value of n\n");
  scanf("%d", &n);

  printf("Enter %d values\n", n);
  for (int i = 0; i < n; i++)
  {
                                 // the space at the beginning of "%[^\n]"
                                 // gets rid of the \n which stays in the input buffer
    scanf(" %[^\n]", name);      // also there sis no 's' at the end of the "%[^\n]" specifier 
    printf("name = %s\n", name); // for testing purposes
  }
}

But this doesn't actually make much sense because the program is asking for n names, but at each run of the for loop the previous name will be overwritten with the new name.

Also be aware that scanf("%[^\\n]", name); is problematic because if the user types more than 99 characters you'll get a buffer overflow.

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