Thread: Reading in string and integer arrays

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    7

    Reading in string and integer arrays

    On a slightly different problem, I would like some assistance on how i would code the following programs.

    I want to develope a programe that reads a series of characters from a string stored in a text file. The characters are numbers in the text file. Then I need to compute a sum from these numbers. My program should read lines of text from a standard input. Each line will contain a single positive integer.


    I have been given the following code to start with.
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    int main() {
    constant size_t maxLineLen =  1024      ;
    char line[ maxLineLen];
    
    while(fgets(line, maxLineLen, stdin) != NULL) {
    printf("%s", line);
    }
    }
    Given a positive integer, find the sum of its constituent digits.

    My mindmap for the sum value, if you forgive the term, is presented below.

    1. Read the string from input
    2. Convert each of the character in the string into an integer
    3. Read each integer into an array, by using a for loop.
    4. In the loop assign variable named sum to zero, each iterstion pf the loop will sum the next arrau value to the previous value named sum.
    5. Print the sum value

    Write a program that finds the greatest difference between integers in a list. The list can contain positive and negative integers

    My program should read lines from a standard input. Each line contains a comma seperated list of integers.
    For each input list, print to standard output the greatest difference between any two integers in the list. Print each difference on its own line.
    Input example 4, -9,-3,0,7,9

    1. Repeat steps 1-3 .
    2. In the loop calculate the difference between the all other values in the array from the first value.
    3. The next iteration will calculate the difference the other values in the array from the second value.
    4. Etc.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,615
    So something like this
    Code:
    // process something looking like this
    // 4, -9,-3,0,7,9
    void parseLine(char *buff) {
        // code
    }
    
    int main ( ) {
        while(fgets(line, maxLineLen, stdin) != NULL) {
            printf("%s", line);
            parseLine(line);
        }
    }
    sscanf and strtok may be interesting functions to look into.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2019
    Posts
    7

    Reading in string and integer arrays

    Thank you for your that info. I am a beginner so forgive the oversimplification.

    For the first problem, i.e sum i used the following
    Code:
    include<stdio.h>
    #include<stdlib.h>
    
    	const size_t maxLineLen=1032;
    	char line[maxLineLen+1];
     int count, sum;
    int main(){
      
        while(fgets(line, maxLineLen, stdin) != NULL) {
        	for(count=1; count<maxLineLen;count ++){
        	  sum=0;
        			sum+= &line[count];
            printf("%s", sum);
            
        }
        }
    }
    Output I get
    234
    34
    4
    As oppppsed to the sum of 10

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,615
    Well your first problem would be that '2' != 2

    You need to convert your character representation into its numeric representation.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Nov 2019
    Posts
    7
    I have used strtol, but having difficulty transferring converted int values into an array

    include<stdio.h>
    #include<stdlib.h>
    Code:
    	const size_t maxLineLen=1032;
    	char line[maxLineLen+1];
    char *ptr;
     int count, ret[10], sum;
    int main(){
      
        while(fgets(line, maxLineLen, stdin) != NULL) {
        	for(count=1; count<maxLineLen;count ++){
        	  sum=0;
        	  
        	  ret[count] = strtol(stdin, &ptr, 10);
        			sum+= (int)ret[count];
           printf("%s", sum);
            
        }
        
        
        }
    }

  6. #6
    Registered User
    Join Date
    Nov 2019
    Posts
    7
    Quote Originally Posted by ronanmac01 View Post
    I have used strtol, but having difficulty transferring converted int values into an array

    include<stdio.h>
    #include<stdlib.h>
    Code:
    	const size_t maxLineLen=1032;
    	char line[maxLineLen+1];
    char *ptr;
     int count, ret[10], sum;
    int main(){
      
        while(fgets(line, maxLineLen, stdin) != NULL) {
        	for(count=1; count<maxLineLen;count ++){
        	  sum=0;
        	  
        	  ret[count] = strtol(stdin, &ptr, 10);
        			sum+= (int)ret[count];
           printf("%s", sum);
            
        }
        
        
        }
    }
    Can you explain what code I would need to incorporate into this program so I can get it to work

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,615
    Like this.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
      char buff[100];
      if ( fgets(buff,sizeof(buff),stdin) ) {
        char *ptr = buff;
        long v = strtol(ptr,&ptr,10);
        printf("v=%ld, tail=%s",v,ptr);
      }
      return 0;
    }
    
    $ ./a.out 
    1,2,3
    v=1, tail=,2,3
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User Sir Galahad's Avatar
    Join Date
    Nov 2016
    Location
    The Round Table
    Posts
    89
    If you're only going to be working with plain ints why not just use atoi()?

  9. #9
    Registered User
    Join Date
    Nov 2019
    Posts
    7
    Does the atoi() function not leave you with unpredictable results.

  10. #10
    Registered User
    Join Date
    Nov 2019
    Posts
    7
    Hi thank you for your assistance again. Before I develop code to summate each digit of the number , I will need to assign each digit to an array.

    As v is a const integer I will need to convert it to an array, I am not sure how to do this, i presume I would pass for loop through strtol() function.
    My mindmap would be.
    String to char array, each member in array is converted to long int via strtol(), then converted numeric is assigned to an empty array.
    I would then have an empty sum array which fills in each increment in a for loop.
    Something like
    [code] for(i=0, i<sizeof(buff), i++);
    sum += vnumeric_array[i];
    [code\n]

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,425
    Quote Originally Posted by Sir Galahad View Post
    If you're only going to be working with plain ints why not just use atoi()?
    The problem with atoi is that it does not provide a way to distinguish between an error and a valid conversion to 0.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User Sir Galahad's Avatar
    Join Date
    Nov 2016
    Location
    The Round Table
    Posts
    89
    Quote Originally Posted by ronanmac01 View Post
    Hi thank you for your assistance again. Before I develop code to summate each digit of the number , I will need to assign each digit to an array.

    As v is a const integer I will need to convert it to an array, I am not sure how to do this, i presume I would pass for loop through strtol() function.
    My mindmap would be.
    String to char array, each member in array is converted to long int via strtol(), then converted numeric is assigned to an empty array.
    I would then have an empty sum array which fills in each increment in a for loop.
    Something like
    [code] for(i=0, i<sizeof(buff), i++);
    sum += vnumeric_array[i];
    [code\n]

    No need, that's what strtol does for you: converts a string to a long.

    Quote Originally Posted by laserlight View Post
    The problem with atoi is that it does not provide a way to distinguish between an error and a valid conversion to 0.
    Well that's true, good point.
    Last edited by Sir Galahad; 11-25-2019 at 03:54 PM.

  13. #13
    Registered User
    Join Date
    Dec 2017
    Posts
    794
    Quote Originally Posted by laserlight View Post
    The problem with atoi is that it does not provide a way to distinguish between an error and a valid conversion to 0.
    It's worse than that. It doesn't have a specified way to deal with out-of-range values at all. It doesn't necessarily return 0 (or INT_MIN/INT_MAX) in that case. Just garbage.
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

  14. #14
    Registered User
    Join Date
    Nov 2019
    Posts
    7
    Code:
     Thank you for your reply and suggestion. I have developed my code and does sucessfully calculate, and print the sum of intgers in the integer array.
    However I would like to read in string using fgets, can you share what code would need to be included?
    I have removed the fgets and strtol functions and created a function named convert(c) that loops through each character of the array converting each to an integer.
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int* convert(char* c)
    {
        int len=strlen(c),i;
        int *a=(int*)malloc(len*sizeof(int));
        for(i=0;i<len;i++)
            a[i]=c[i]-48;
        return a;
       
    }
    int main(int argc, char const *argv[])
    {
        int i;
        char c[100];
    
        int sum=0;
        scanf("%s",c);
        int *a=convert(c);
            int len=strlen(c);
        for(i=0;i<len;i++){
            sum+= a[i];
       
            }
            printf("%d", sum);
        free(a);
       
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 11-23-2013, 08:23 PM
  2. Reading integer from string
    By dr_kaufman in forum C Programming
    Replies: 2
    Last Post: 04-30-2011, 09:40 AM
  3. Replies: 4
    Last Post: 12-04-2009, 10:22 AM
  4. Replies: 5
    Last Post: 09-19-2003, 03:47 AM
  5. Reading the input file into integer arrays
    By supaben34 in forum C++ Programming
    Replies: 3
    Last Post: 12-06-2002, 07:04 PM