Why does my program exit after taking an input? - c

Consider:
#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 exits the program. The for loop never runs. It ran successfully for the first time, but after that it just exits the program.
There were some answers that said it will not print anything. I don’t want it to print just to take input n times. It is not doing that.
My aim is to take n as input and then 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.

Related

How do you use scanf in a for loop so it does not stop looping on the first try?

for(int i=0;i<num; i++)
{
char word[32];
scanf(" %[^\n]s",word);
makeDictionary(word, readDictionary);
}
I have a program where I want to ask user for certain strings n times (with spacing allowed). However, when they input for example n = 2, it only loops once and exists. I know there is something wrong with my scanf.
I do Java and I'm a beginner at C. The way strings are done is very different.
This code can help you:
#include <stdio.h>
#include <string.h>
int main()
{
int N;
do
{
printf("Give me number of words :");
scanf("%d",&N);
}while(N<1);
for(int i=0;i<N;i++)
{char str[20];
printf("\nGive me the %d word :",i+1);
scanf("%s[^\n]",str);
printf("%s",str);
}
}

How do I get input for an array from a user in C programming?

I am new to C and I've run into a bit of a problem when it comes to user input for an array.
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, i;
int score [n];
printf("Number of scores: ");
scanf("%d", &n);
for(i=0; i<n; i++){
printf("score: ");
scanf("%d", &score[i]);
}
return 0;
}
It does not matter what value I set for n. It always prompts the user 4 times.
As mentioned in comments, you must change this:
/* bad */
int score [n];
printf("Number of scores: ");
scanf("%d", &n);
into this
/* good */
printf("Number of scores: ");
scanf("%d", &n);
int score [n];
This since C executes code from top to bottom like when you are reading a book. It will not "double back" a few rows above and fill in n once it has been entered by the user. At the point where you declare int score [n], n must already be known.
If your using an array with unknown size during compilation, I would suggest using memory allocation. So the user determines the array size while running the program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, i;
int *score;
printf("Number of scores: ");
scanf("%d", &n);
score = (int *)malloc(sizeof(int)*n);
for(i=0; i<n; i++){
printf("score: ");
scanf("%d", &score[i]);
}
free(score)
return 0;
}
The malloc function allocates memory with the size of n and returns a pointer to the allocated memory.

Loop doesn't work correctly (strings)

I'm writing a program that will sort words you input alphabetically, but I found it impossible to progress because the loop doesn't work as intended.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
char string[50][50];
int i, n;
printf("Insert the number of strings: ");
scanf("%d ", &n);
for(i=0; i < n; i++)
{
printf("Insert %d. string: ", i+1);
fgets(string[i],50,stdin);
}
return 0;
}
I tried using gets() and tried to use fgets(), but the result is the same. It prints:
Insert 1. string: Insert 2. string:
Then you can insert strings, but 1 less than specified.
you have semicolon after for loop !!!

why the first string is printed repeatly irrespective of number of test cases and how to correct it. Please correct it. language is c used

#include <stdio.h>
#include <string.h>
int main(void) {
int i, j, t;
scanf("%d", &t); // enter the number of test cases
getchar();
char input[11111];
for(i=0; i<t; i++){
scanf("%[^STOP]", input); // take input till STOP will come
printf("%s\n", input);
// this code print first input as many time as number of test cases in the code that will we provide through variable t;
}
return 0;
}
Change your code to
#include <stdio.h>
#include <string.h>
int main(void) {
int i, j, t;
char ch;
scanf("%d", &t); // enter the number of test cases
getchar();
char input[11111];
for(i=0; i<t; i++){
scanf("%[^STOP]", input); // take input till STOP will come
while((ch=getchar())!='\n'&& ch!= EOF);
printf("%s\n", input);
// this code print first input as many time as number of test cases in the code that will we provide through variable t;
}
return 0;
}
The problem was caused because of buffering. scanf() sends \n to the input buffer and the next scanf() reads this. That is what caused the problems.
If you want to know more about this, just search for input buffer in Stack Overflow or in Google. This problem has been discussed over and over many times.

How to get multiple inputs in one line in C?

I know that I can use
scanf("%d %d %d",&a,&b,&c):
But what if the user first determines how many input there'd be in the line?
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int numInputs;
int *input;
printf("Total number of inputs: ");
scanf("%d", &numInputs);
input = malloc(numInputs * sizeof(int));
for (int i=0; i < numInputs; i++)
{
printf("Input #%d: ", i+1);
scanf("%d", &input[i]);
}
// Do Stuff, for example print them:
for (int i=0; i < numInputs; i++)
{
printf("Input #%d = %d\n", i+1, input[i]);
}
free(input);
}
Read in the whole line, then use a loop to parse out what you need.
To get you started:
1) Here is the manual page for getline(3):
http://man7.org/linux/man-pages/man3/getline.3.html
2) Some alternatves to getline:
How to read a line from the console in C?
3) Consider compressing spaces:
How do I replace multiple spaces with a single space?
4) Use a loop for parsing. You might consider tokenizing:
Tokenizing strings in C
5) Be careful and remember that your user could enter anything.
#include <conio.h>
#include <stdio.h>
main()
{
int a[100],i,n_input,inputs;
printf("Enter the number of inputs");
scanf("%d",&n_input);
for(i=0;i<n_input;i++)
{
printf("Input #%d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n_input;i++)
{
printf("\nInput #%d: %d ",i+1,a[i]);
}
}
/*
_______________This program is in C Programming Language_______________
We have to directly enter all the elements in one line giving spaces between them. Compiler will automatically ends the for loop I have used and assign the value to their respective variables or array indexes. Below program and output will give you better understanding.
*/
#include <stdio.h>
int main()
{
//taking no of inputs from user
int len;
printf("Enter the number of inputs you want to enter : ");
scanf("%d", &len);
int i;
//defined an array for storing multiple outputs
int arr[100];
//included a printf statement for better understanding of end user
printf("Enter the inputs here by giving space after each input : ");
/*here is the important lines of codess for taking multiple inputs on one line*/
for (i=0;i<len;i++)
{
scanf("%d", &arr[i]);
}
printf("Your entered elements is : ");
for (i=0;i<len;i++)
{
printf("%d ", arr[i]);
}
}
/*
OUTPUT :
Enter the number of inputs you want to enter : 5
5 5 5 8 7
Your entered elements is : 5 5 5 8 7
*/

Resources