How do I break the one dimensional array when condition met? - c

I am trying to enter an array of numbers (only integers for now) and what I wan't to do is if the user enters all the needed numbers, give him the ability to break the operation of entering numbers and skip to printing the entered numbers. My code is below. So the thing is, I've set 100 array elements, but if only have 5 to enter I don't wan't to enter the other 95.
Commented code is what I've tried and it didn't work. ( I work in CodeBlocks and am a total beginner, so I'm still learning this...)
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Declaring variables
int one_d_array[100],counter=0;
printf("Enter a list of numbers(max. 100)\nTo end, enter two zeros (00)\n");
for (counter=0;counter<5;counter++){
scanf("%d",&one_d_array[counter]);
/*if (one_d_array[counter]==00){
break;
}*/
}
printf("Entered list is:\n");
for (counter=0;counter<5;counter++){
printf("%d\n",one_d_array[counter]);
}
}
return 0;
}

fgets can be used to input a line. If the line is 00 exit the loop. Otherwise sscanf tries to scan a number.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void)
{
int one_d_array[100],each=0,counter=0;
char input[99] = "";
printf("Enter a list of numbers(max. 100)\nTo end, enter two zeros (00)\n");
while ( 1){
if ( fgets ( input, sizeof ( input), stdin)) {//get a line
if ( strcmp ( input, "00\n") == 0) {//exit on 00
break;
}
if ( ( sscanf(input, "%d",&one_d_array[counter])) != 1) {// != 1 means sscanf failed
printf("could not scan a number try again\n");
continue;
}
counter++;
printf("numbers input: %d\n\n", counter);
if ( counter >= 100) {
break;
}
}
else {
fprintf ( stderr, "problem reading input\n");
exit ( 1);
}
}
printf("Entered list is:\n");
for (each=0;each<counter;each++){
printf("%d\n",one_d_array[each]);
}
return 0;
}

Variable names cannot start with a number, so I've edited it accordingly.
#include <stdio.h>
#include <stdlib.h>
int main(){
//Declaring variables
int oneD_array[100],counter=0, num=0;
char c[3];
do{
printf("Enter your %d number, q to quit", counter+1);
scanf("%s",&c);
if(c == "q" || c == "Q"){
break;
}
else{
num = atoi(c);
oneD_array[num];
counter++;
}
}while(c != "q");
printf("Entered list is:\n");
for (int i = 0;i<counter;i++){
printf("%d\n",oneD_array[i]);
}
}
return 0;
}

Related

Scanf for integer not working as expected when I input float or string

I'm new to C language and I'm writing this code for fun. In here I take username first and then I'm taking a guess number from the user. And I wrote a function to check whether number is int or not (only need integer inputs.)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
char userName[30];
int userGuess, check;
int checkGuess(int, int);
printf("Enter your name - ");
scanf("%s",&userName);
int i = 0;
while(++i<=10)
{
printf("Enter Your Guess: ");
check = scanf("%d",&userGuess);
checkGuess(userGuess, check);
}
return 0;
}
int checkGuess(int userGuess, int check)
{
if(check == 1)
{
printf("yes int, %d.\n",userGuess);
} else
{
printf("Not int\n");
}
}
However when I put integers it works fine, but when I put a string or a float it just runs the loop till end.
You need to flush stdin when scanf fails
while (i < 10)
{
printf("Enter Your Guess: ");
check = scanf("%d", &userGuess);
if (check != 1)
{
// Flush stdin
while ((check = fgetc(stdin)) != '\n' && check != EOF);
}
else
{
// Increment i only when scanf has success
i++;
}
}
Take a look to Why to use fgets() over scanf() in C?

Error output if a wrong number or char is inserted while in a loop

I'm trying to make a program that generates random numbers and has the user guessing the answer of the sum of those numbers! I don't know how to send a wrong input message if the user inserts say the letter d. And if he inserts the letter s or S the program just finishes the for loop.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include<time.h>
main(void){
int num1,num,result,resultuser;
int i;
//char s,S;
srand(time(NULL));
printf("Numeros:");
for(i=0 ; i<10 ; i++) {
num1 = ( rand()%50 );
num = ( rand()%50 );
printf("Qual o resultado da conta: %i + %i =", num,num1);
scanf("%i",&resultuser);
result = num + num1;
if (result == resultuser){
printf("Correto!\n\n");
} else{
printf("Errado!\n\n");
}
}
}
The return code for scanf is the number of elements successfully parsed. In your situation, you would expect it to be 1 if the integer is successfully parsed.
If you save the return code from scanf, you can identify when the number of parsed elements was 0, ie, that it couldn't parse an integer as you requested. At this point, you can print to the user that they did not enter a valid number.
Read input using fget() and then parse it for the int or letter.
printf("Qual o resultado da conta: %i + %i =", num,num1);
char buffer[100];
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
// EOF or error detect, quit the loop
break;
}
// Test if a number was found
if (sscanf(buffer, "%i", &resultuser) != 1) {
// use `resultuser`
} else if (buffer[0] == 's' || buffer[0] == 'S') {
// exit the loop normally as S was found
break;
} else {
// bad input detected
}

How to find the length of an input

i am trying to measure how many numbers my input has.
if i input the following line: 1 2 65 3 4 7,
i want the output to be 8.but what I'm getting is 1 2 3 4.
#include <stdio.h>
int main(void) {
int data;
int i = 1;
while (i <= sizeof(data)) {
scanf("%d", &data)
printf("%d", i);
i++;
}
}
You are printing i which have no relation to the input at all. So no matter what your input is, you'll get 1234
sizeof(data) is the same as sizeof(int), i.e. a constant with value 4 on your system.
If you want to count the number of numbers and don't care about the value of the individual number, you could do:
#include <stdio.h>
#include <ctype.h>
int main(void) {
char s[1024];
char* p;
int i = 0;
fgets(s, 1024, stdin);
p=s;
while (*p != '\0')
{
if (!isdigit(*p))
{
p++;
}
else
{
i++; // Found new number
// Search for a delimiter, i.e. skip all digits
p++;
while (*p != '\0' && isdigit(*p))
{
p++;
}
}
}
printf("We found %d numbers", i);
return 0;
}
Output:
We found 6 numbers
Notice that this code will accept any non-digit input as delimiter.
put the scanf before the while-loop and move the printf after the while-loop.
I'm also providing solution according to my openion.
#include <stdio.h>
int main(void) {
int data = 1;
int i = 0;
// here data != 0 is trigger point for end input,
// once you done with your inputs you need to last add 0 to terminate
while (data != 0) {
scanf("%d", &data)
printf("Collected Data: %d", data);
i++;
}
printf("Total number of inputs are %d.", i);
}
Hope this solution helps you.
Here is my solution:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i = 0;
int data[100]; // creating an array
while(1) { // the loop will run forever
scanf("%d", &data[i]);
if (data[i] == -1) { //unless data[i] = -1
break; // exit while-loop
}
i++;
}
printf("%d\n", data[2]); // print 2nd integer in data[]
return 0;
}
Do not forget to hit enter once you entered an int. Output of the program:
2
56
894
34
6
12
-1
894
Hope that helps. :)

How to prevent non-numeric input in C?

I wrote a small C program which will get an input from the user and check if the input is even or odd.
#include<stdio.h>
int main()
{
int n;
printf("Enter an integer number: ");
scanf("%d",&n);
if(n%2 == 0)
{
printf("\n%d is an EVEN number.\n",n);
}
else
printf("\n%d is an ODD number.\n",n);
return 0;
}
but when I enter an alphabet or a symbol, it shows the output as 0 and says input is EVEN. How can I prevent user from entering alphabets and symbols? What's the easiest way to do that?
You have to check the return value of scanf. From the documentation:
Return Value
Number of receiving arguments successfully assigned, or EOF if read failure occurs before the first receiving argument was assigned.
Applied to your code:
#include <stdio.h>
#include <stdlib.h>
int
main()
{
int n;
printf("Enter an integer number: ");
if (scanf("%d", &n) != 1)
{
printf("This is not a number.\n");
return EXIT_FAILURE;
}
else if (n % 2 == 0)
{
printf("\n%d is an EVEN number.\n", n);
return EXIT_SUCCESS;
}
else
{
printf("\n%d is an ODD number.\n", n);
return EXIT_SUCCESS;
}
}
Simply check the return value of scanf - it'll tell you how many format objects were successfully parsed. In this case, it'll return 1 if it could parse an int, and 0 if it couldn't.
If the input is an integer, then scanf() will return 1 so you can check
if (scanf("%d", &integer) != 1)
invalidInput();
to ask the user again you should know that there could be characters left in the stdin that need to be read so you can flush them with getchar() so a complete function would be
int scanint(const char *const message)
{
int value;
printf("%s > ", message);
while (scanf("%d", &value) != 1)
{
int chr;
printf("\tinvalid input...\n");
do {
chr = getchar();
} while ((chr != EOF) && (chr != '\n'));
printf("%s > ", message);
}
return value;
}
and you can use it like this
int main()
{
int value = scanint("please input an integer");
printf("your input was: %d\n", value);
return 0;
}
I can give you two approaches:
very easy — check for return value of scanf(). 1 indicates success (integer read) and 0 if any non-integer is put in there (or EOF on EOF).
by writing code for it:
#include <ctype.h>
#include <stdlib.h>
int isNumeric (const char * s)
{
if (s == NULL || *s == '\0' || isspace(*s))
return 0;
char * p;
strtod (s, &p);
return *p == '\0';
}
Now in this case your scanf has to take a string from user and then pass that string to the function isNumeric().

Validating User Input String

Here's part of the description of the assignment: The program must stop
accepting input when the user enters the word done. Assume that no word is
more than 20 letters long.
I have to validate that if a word is more than 20 characters thy will get an error message and have to retype again. Also when I type done, the program should end. Im not sure how to write these statements correctly. When I run it and type more then 20 characters it gives me an error - Expression: L("Buffer is too small" &&0)
Here's my Code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCHAR 20
int charcount(char []);
int main()
{
char message[MAXCHAR];
int numofchar;
printf("Enter any word to display how many characters that word has.\nA word CANNOT be more than 20 charatcers long.\n");
printf("When you are finished type the word done.\n");
do
{
printf("\nEnter a word: " );
gets_s(message, MAXCHAR);
numofchar = charcount(message);
while ( numofchar > MAXCHAR)
{
printf("The word enterd is more then 20 characters. Try again.\n");
printf("Enter a word: " );
gets_s(message, MAXCHAR);
}
printf("The word %s has %d characters.\n", (message),numofchar);
} while ( (message,MAXCHAR) != 'done');
printf("\nEnd of program.\n");
system ("PAUSE");
return 0;
}
int charcount (char list[])
{
int i, count = 0;
for(i = 0; list[i] != '\0'; i++)
count++;
return(count);
}
To detect an error, you simply need to check the return value of get_s:
http://msdn.microsoft.com/en-us/library/5b5x9wc7%28v=vs.90%29.aspx
int main()
{
char message[MAXCHAR], *s;
int numofchar;
...
do
{
printf("\nEnter a word: " );
s = gets_s(message, MAXCHAR);
if (!s) {
<< some error handling code goes here >>
...

Resources