How to find the length of an input - c

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. :)

Related

how can i sum realy big number? [duplicate]

This question already has answers here:
Digital Root in c
(2 answers)
Closed 11 months ago.
So you have to do:
11 = 1+1 = 2
3578 = 3+5+7+8 = 23 = 2+3 = 5
But the problem is that the number can be very large(consist of 10,000 digits)
But even with the easiest entrances it doesn't work:
Input : 11
Output: 2798 (and it always changes, but remains a 4-digit number)
Can someone explain why is this happening?
And how can I summarize each digit of a very large number?
You got that huge number becuase your program is adding the ASCII value of various characters.
Some improvements:
Don't use "%s", use "%<WIDTH>s", to avoid buffer-overflow
Use size_t to iterate through an array, instead of unsigned long long int
Instead of using bare return 0;, use return EXIT_SUCCESS;, which is defined in the header file stdlib.h.
always check whether scanf() input was successful or not
Don't check for '\n', because string from scanf() ends at both SPACES and NEWLINE.
adding +1 to array size for NULL terminating character
Use "%zu" instead of "%lld" for size_t
Final Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void) {
char buffer[10001] = {0};
if(scanf("%10000s", buffer) != 1)
{
perror("bad input");
return EXIT_FAILURE;
}
size_t result = 0;
for(size_t i = 0; buffer[i]; i++) {
if(isdigit(buffer[i])){
result += buffer[i] - '0';
}
else {
perror("only digits are valid");
return EXIT_FAILURE;
}
}
printf("%zu\n", result);
return EXIT_SUCCESS;
}
Output:
1112
5
TRY IT ONLINE
You can do it without occupying memory
#include <ctype.h>
#include <stdio.h>
int main(void) {
int sum = 0;
for (;;) {
int ch = getchar();
if (!isdigit((unsigned char)ch)) break; // leave loop with ENTER, EOF, 'a', ...
sum += ch - '0';
}
printf("sum of digits is %d.\n", sum);
return 0;
}
Edit: see code running at ideone
Wiki Digital Root provides a shortcut for getting the final single digit.
Validate your input string has only numeric digits
Find the sum of all digits in ASCII form
Make use of congruence formula to get the result.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_NUM_LEN 10000
int digitRoot (int n) {
if (0 == n) return 0;
return (0 == (n % 9)) ? 9 : (n % 9);
}
int main () {
char str_num [MAX_NUM_LEN];
printf ("Finding Digital Root\nEnter a number : ");
if (NULL == fgets (str_num, sizeof (str_num), stdin)) {
perror ("Reading input string");
return 2;
}
int slen = strlen (str_num);
// remove new line if found
if ('\n' == str_num[slen - 1]) str_num[--slen] = '\0';
// validate input
int digitSum = 0;
for (int ni = 0; ni < slen; ++ni) {
if (!isdigit ((unsigned char) str_num[ni])) {
printf ("\nERROR: Invalid digit [%c]\n", str_num[ni]);
return 1;
}
digitSum += str_num[ni] - '0';
}
printf ("\nDigital Root is [%d]\n", digitRoot (digitSum));
return 0;
}

Comparing digits of two inputs to see if they are the same

I am currently trying to finish a code where a user inputs two 5 digit long numbers. The code then checks to see if there are any identical numbers in the same spot for the two numbers and displays how many identical numbers there are in the same spot of the two inputs. (ex. comparing 56789 and 94712 there would be one similar digit, the 7 in the 3rd digit place.) As of now I have been able to break down the inputs into the digits in each spot, I just need help comparing them. Originally I thought I could just create an int that would serve as a counter and use modulus or division to output a 1 whenever the digits were the same, but I have been unable to put together a formula that outputs a 1 or 0 depending on if the digits are alike or not.
suppose you know the length of strings n (as a condition you would need them to be equal, if they differ in length other validation is needed)
//n is the length of string
for(int i=0;i<n;i++)
{
if(string1[i]==string2[i])
{
//do something, make a counter that increments here...
//also save index i, so you can tell the position when a match occured
}else
{
//do something else if you need to do something when chars didnt match
}
}
Here you when i=0, you are comparing string1[0] with string2[0], when i=1, you compare string1[1] with string2[1] and so on.....
I'd recommend reading the two in as strings or converting to strings if you have the ability to. From there it's a simple string compare with a counter. Something like this:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int is_numeric(char *str)
{
while (*str)
if (!isdigit(*str++))
return (0);
return (1);
}
int main(void)
{
char num1[32];
char num2[32];
int count = 0;
printf("Digit 1\n>> ");
if (scanf("%5s", num1) != 1 || !is_numeric(num1))
return (0);
printf("Digit 2\n>> ");
if (scanf("%5s", num2) != 1 || !is_numeric(num2))
return (0);
if (strlen(num1) != 5 || strlen(num2) != 5)
return (0);
for (int i=0; i<5; ++i)
if (num1[i] == num2[i])
++count;
printf("%d\n", count);
return (0);
}
You can do it very easy using modulo (%) and divide (/). First you do % 10 to get the least significant digit and do the compare. Then you do / 10 to remove the least significant digit. Like:
#include <stdio.h>
#include <string.h>
int main(void) {
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1 || i1 < 10000 || i1 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1 || i2 < 10000 || i2 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
for (i=0; i<5; ++i)
{
if ((i1 % 10) == (i2 % 10)) ++cnt; // Compare the digits
i1 = i1 / 10;
i2 = i2 / 10;
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
It can also be done using strings. Read the input as unsigned int and then convert the value to a string using snprintf and finally compare the two strings character by character.
Something like:
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[32];
char str2[32];
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str1, 32, "%u", i1);
if (strlen(str1) != 5) // Convert to string
{
printf("input error - not 5 digits\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str2, 32, "%u", i2); // Convert to string
if (strlen(str2) != 5)
{
printf("input error - not 5 digits\n");
return 0;
}
for (i=0; i<5; ++i)
{
if (str1[i] == str2[i]) ++cnt; // Compare the characters
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
The reason for taking the input into a unsigned int instead of directly to a string is that by doing that I don't have to check that the string are actually valid numbers (e.g. the user type 12W34). scanf did that for me.

C storing strings into an array

I'm working in a problem from the "C programming a Modern Approach 2nd Edition" text. I want to write a program that writes the smallest and largest words. The program stops accepting inputs when the user enters a 4-letter word.
I'm using an array of strings to solve this but I can't even get my program to store words in it.
#include <stdio.h>
#include <string.h>
#define WORD_LEN 20
int main()
{
char word[WORD_LEN]={0},ch;
char *a[10]={}; //Max 10 words in the array
int i=0,j;
for(;;)
{
printf("Enter a word: ");
fgets(word,WORD_LEN,stdin);
strtok(word, "\n"); //removes newline
a[i] = word;
if(strlen(word) == 4) //if word is 4 characters
break; //break out of loop
i++;
}
for(j=0;j<i;j++) //displaying array
printf("%s\n",a[j]);
return 0;
}
Output:
Enter a word: Analysis
Enter a word: Martin
Enter a word: Jonathan
Enter a word: Dana
Dana
Dana
Dana
Any idea into what I'm doing wrong? Thanks.
As BLUEPIXY mentioned, you are storing same address in all a[i]s. So at the end of the loop, it prints the last output i times.
Solution:
You need to allocate memory for a[i] and copy the strings.
#include <stdio.h>
#include <string.h>
#define WORD_LEN 20
#define MAX_NUM_WORD 10 //Max 10 words in the array
int main()
{
char word[WORD_LEN]={0},ch;
char *a[MAX_NUM_WORD]={0};
int i=0,j;
for(;;)
{
printf("Enter a word: ");
fgets(word,WORD_LEN,stdin);
strtok(word, "\n"); //removes newline
a[i] = malloc(sizeof(char)* (strlen(word)+1)); //1 for '\0'
strcpy(a[i], word);
i++;
if(strlen(word) == 4) //if word is 4 characters
break; //break out of loop
//i++; //You will be missing last 4 letter word if i++ is here.
if(MAX_NUM_WORD <= i) //You can store only MAX_NUM_WORD strings
break;
}
for(j=0;j<i;j++) //displaying array
printf("%s\n",a[j]);
//Your other code.
for(i=0; i<MAX_NUM_WORD && NULL != a[i]; i++)
free(a[i]); //Free the allocated memory.
return 0;
}
Adding to others answers, when using malloc to allocate memory for your strings, it is good to also check the return value of void* pointer returned from it.
Additionally, it is also safe to check the return value of fgets, just to be super safe.
This solution demonstrates these points:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LEN 20
#define MAX_NUM_WORD 10
#define EXIT_LEN 4
int
main(void) {
char word[WORD_LEN];
char *a[MAX_NUM_WORD];
int i = 0, wrd;
while (i < MAX_NUM_WORD) {
printf("Enter a word: ");
if (fgets(word, WORD_LEN, stdin) != NULL) {
word[strlen(word)-1] = '\0';
}
a[i] = malloc(strlen(word)+1);
if (a[i] == NULL) {
fprintf(stderr, "%s\n", "Malloc Problem");
exit(EXIT_FAILURE);
}
strcpy(a[i], word);
i++;
if (strlen(word) == EXIT_LEN) {
break;
}
}
// Print and free, all at once.
for (wrd = 0; wrd < i; wrd++) {
printf("%s\n", a[wrd]);
free(a[wrd]);
a[wrd] = NULL;
}
return 0;
}

Input to array of strings won't show?

I'm in C and I'm supposed to have an input of numbers (don't know how many) formatted into one column without storing them into an array of integers. I can't figure out why my code won't read the input and out put it. Please help.
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
char *nums[400];
for (i=0; i<nums; i++) {
scanf(nums[i]);
printf( "%.*s", 3, nums[i] );
}
return 0;
}
You have an array of 400 pointers, but you've never initialized them. Instead, you could declare a 2-dimension array:
char nums[400][4];
Then you're trying to use nums as a limit to the for loop. What you actually want is the number of elements in nums, which is sizeof(nums)/sizeof(nums[0]); or you could define a macro that specifies the size of the array.
Next, you left out the format string argument to scanf().
#include <stdio.h>
#include <stdlib.h>
#declare SIZE 400
int main()
{
int i;
char *nums[SIZE][4];
for(i=0; i<SIZE; i++){
scanf("%3s", nums[i]);
printf( "%.*s", 3, nums[i] );
}
return 0;
}
As Baramar correctly and thoroughly explained your main problems, I think I might have a different understanding of your problem. You want a given string of number, e.g.: 2134567896543245678 and print it out in a single column, neatly formated in rows of three digits each like that:
213
456
789
654
324
567
8
without an intermittent array of integers.
That could be done like e.g.: this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 512
int main()
{
int res;
// for the scanf input, set all to '\0'
char buffer[BUFFER_SIZE + 1] = { '\0' }, *idx;
size_t len, i;
// restrict max-size to BUFFER_SIZE
res = scanf("%512s", buffer);
if (res != 1) {
exit(EXIT_FAILURE);
} else {
if (strcmp(buffer, "exit") == 0) {
exit(EXIT_SUCCESS);
}
// TODO: check if the buffer contains all digits
len = strlen(buffer);
idx = buffer;
for (i = len; i >= 3; i -= 3, idx += 3) {
printf("%.3s\n", idx);
}
// last entries, if any
if (*idx != '\0') {
printf("%s\n", idx);
}
}
exit(EXIT_SUCCESS);
}
If you get actual integers in a row like e.g.: 12 3123 23478 34 5456 567456 567 678 you can use something like that:
EDIT
After the comment by the OP to use floating points I changed the code to accept input of the form:
24722.319352 51433.662233
56087.991042 49357.684934 67875.375848 68421.563197
54521.615295
22744.470483
38097.001461 80878.250982
92131.575748 7217.137271
20750.671365 7620.695008 37118.391541 28655.609469 46885.110202 87114.202312
46462.577299
20557.716648
And the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNUM 400
int main()
{
int res;
int i = 0, m;
// input and two temporary variables
double in, in1, in2;
for (m = 0; m < MAXNUM; m++) {
res = scanf("%lf", &in);
if (res != 1) {
break;
} else {
switch (i) {
case 0:
// set value of first temporary variable to input
in1 = in;
// increment indicator indicating position in output row
i++;
break;
case 1:
in2 = in;
i++;
break;
case 2:
// print the three numbers and a newline
fprintf(stdout, "%f %f %f\n", in1, in2, in);
// reset counter
i = 0;
break;
}
}
}
// if there are still numbers, print them
if (i != 0) {
if (i == 1) {
fprintf(stdout, "%f\n", in1);
} else {
fprintf(stdout, "%f %f\n", in1, in2);
}
}
exit(EXIT_SUCCESS);
}
Try it out with
$ gcc-4.9 -O3 -g3 -W -Wall -Wextra -std=c11 sc.c -o sc
$ ./sc < floatin
24722.319352 51433.662233 56087.991042
49357.684934 67875.375848 68421.563197
54521.615295 22744.470483 38097.001461
80878.250982 92131.575748 7217.137271
20750.671365 7620.695008 37118.391541
28655.609469 46885.110202 87114.202312
46462.577299 20557.716648
If you enter less than 400 entries you need to end with EOF which can be triggered in most Unix shells with ctrl+d or set an entry to end the entries like e.g.: -1 if all you have is positive numbers and check for it to break out of the loop. If you submit a file like in the example above it works automatically.

How to read 2 lines of integer input in C?

I'm doing a project for my algorithms class and I'm having a lot of trouble with inputs. I'm trying to read an input like this:
6 0 2 3 1 3
5 9 2 1 3
The integers will need to go to
int num1; // num1 = 6
int num2; // num2 = 5
int array1[100]; // array1 = {0, 2, 3, 1, 3, 0, 0, ...}
int array2[100]; // array2 = {9, 2, 1, 3, 0, 0, ...}
The input will come from standard input, in the form of a file. So in terminal running the program would look like this:
cat input.txt | ./a.out
Where input.txt contains the two lines of integers.
Here is my flawed attempt so far:
while(scanf("%d%c", &temp, &ch) > 1){
if (ch != '\n'){
one[count] = temp;
}
else if (ch == '\n'){
count = 0;
two[count] = temp;
}
one[count] = temp;
count++;
if (ch != ' ')
{
printf("Invalid input. Please do int + space.\n");
return -1;
}
if ((temp >= 100) || (temp <= -100))
{
printf("Input is too big, must be between -100, 100.\n");
return -1;
}
if (one[0] < 1){
printf("Input for n cannot be smaller than one!");
return -1;
}
}
I think the main issue is that I'm just not sure how to deal with multiple lines of input. One line of input is fine by me but multiple lines is what trips me over.
You could fetch an entire line of input using the getline function and then iterate over that line, scanning one number at a time using the strtol function.
From the example in your question I assume that you want all remaining entries in the two arrays to be zero so don't forget to zero them out (either manually or using the memset function.).
And also don't forget to free() the buffer getline gave you.
Actually I ended up using scanf, here is the working code below. It really helped to read some of these comments and also refer to K&R
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 100
void shiftArrayBackByOne(int a[]){
for(int i = 1; i <= ARRAY_SIZE; i++){
a[i - 1] = a[i];
}
}
void printArray(int a[], int n){
for(int i = 0; i < n; i++){
printf("%d ", a[i]);
}
putchar('\n');
}
int main(){
int isLineTwo = 0;
int countOne = 0;
int countTwo = 0;
int inputNum;
int num1;
int num2;
int array1[ARRAY_SIZE];
int array2[ARRAY_SIZE];
char ch;
while(scanf("%d%c", &inputNum, &ch) > 0){
//Puts the input into different arrays depeding
//on value of isLineTwo
if (isLineTwo){
array2[countOne] = inputNum;
countOne++;
} else {
array1[countTwo] = inputNum;
countTwo++;
}
//Increment isLineTwo if ch is a 'newline'
if (ch == '\n')
{
isLineTwo++;
}
//Check if user inputs more than 2 lines
if (isLineTwo > 1){
printf("Hey, no more than 2 input lines!\n");
}
}
printArray(array1, countOne);
printArray(array2, countTwo);
num1 = array1[0];
num2 = array2[0];
shiftArrayBackByOne(array1);
shiftArrayBackByOne(array2);
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
printArray(array1, countOne);
printArray(array2, countTwo);
}
Look at my code below. Maybe it helps you.
Generally, if you know how many numbers will be inputted, you can read numbers one by one using scanf("%d", ...) and use fflush() when the expected amount is met to clear any other numbers in the buffer. This example assumes that the first two numbers are the respective lengths of each line. The input could look like:
// example input:
// 4
// 3
// 1 2 3 4
// 5 6 7
int main()
{
int it;
int it1 = 0;
int it2 = 0;
int line1[100];
int line2[100];
scanf("%d", &it1); // amount of line 1 numbers
scanf("%d", &it2); // amount of line 2 numbers
it = 0;
do
{
scanf("%d", &line1[it]);
} while (++it < it1);
fflush(stdin); // clear input buffer
it = 0;
do
{
scanf("%d", &line2[it]);
} while (++it < it2);
return 0;
}

Resources