LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-04-2011, 02:38 PM   #1
silentkill89
LQ Newbie
 
Registered: Aug 2011
Posts: 28

Rep: Reputation: Disabled
adding string of integers


suppose there is a string of integers, which will be 1234567, i want to add them together, so the final answer will be 1+2+3+4+5+6+7 = 28. It there a possible way to add them? this will be the input of client server program,where client enter string of integer, and server will add them up and displayed.
 
Old 09-04-2011, 02:52 PM   #2
colucix
LQ Guru
 
Registered: Sep 2003
Location: Bologna
Distribution: CentOS 6.5 OpenSuSE 12.3
Posts: 10,509

Rep: Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983
In which language? Here is an awk solution:
Code:
echo 1234567 | awk '{for (i=1; i<=length($0); i++) sum = sum + substr($0,i,1); print sum}'
 
Old 09-04-2011, 02:53 PM   #3
silentkill89
LQ Newbie
 
Registered: Aug 2011
Posts: 28

Original Poster
Rep: Reputation: Disabled
sorry, in linux C programming
 
Old 09-04-2011, 02:53 PM   #4
Tinkster
Moderator
 
Registered: Apr 2002
Location: earth
Distribution: slackware by choice, others too :} ... android.
Posts: 23,067
Blog Entries: 11

Rep: Reputation: 928Reputation: 928Reputation: 928Reputation: 928Reputation: 928Reputation: 928Reputation: 928Reputation: 928
What language?

And why do you keep posting programming questions in Linux-Newbie?



Cheers,
Tink

P.S.: Moving to <PROGRAMMING>
 
Old 09-04-2011, 03:09 PM   #5
silentkill89
LQ Newbie
 
Registered: Aug 2011
Posts: 28

Original Poster
Rep: Reputation: Disabled
sorry...it's linux C programming
adding digits of the sum, and also I want to know how to test whether a string contains numeric
 
Old 09-04-2011, 03:23 PM   #6
millgates
Member
 
Registered: Feb 2009
Location: 192.168.x.x
Distribution: Slackware
Posts: 852

Rep: Reputation: 389Reputation: 389Reputation: 389Reputation: 389
a simple function to do this might look like this:
Code:
int getsum(char *string, int length){
    if (!string) return 0;
    int sum = 0;
    
    for (i = 0; i < length; i++) {
        if (isdigit(string[i])) sum += ( string[i] - '0' );
    }
    return sum;
}
if that's not what you want, can you be more specific?
what do you mean by client server program?

Last edited by millgates; 09-04-2011 at 03:29 PM.
 
Old 09-04-2011, 03:38 PM   #7
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD 9.1, Kubuntu 12.10
Posts: 3,078

Rep: Reputation: Disabled
Quote:
Originally Posted by silentkill89 View Post
suppose there is a string of integers, which will be 1234567, i want to add them together, so the final answer will be 1+2+3+4+5+6+7 = 28. It there a possible way to add them? this will be the input of client server program,where client enter string of integer, and server will add them up and displayed.
It looks like you want to sum a string of digits, because the entire string is an integer. What's the purpose of this particular communication between the client and the server? Have you considered separating the digits/integers with spaces? Sticking with the original question, though:
Code:
#include <stdlib.h>

int total(const char *sString)
{
    char *remainder = NULL;
    long value = strtol(sString, &remainder, 10);
    if ((remainder && *remainder) || value < 0) return -1;

    unsigned int total = 0;
    do total += value % 10;
    while ((value /= 10));

    return total;
}
Kevin Barry

Last edited by ta0kira; 09-04-2011 at 04:21 PM. Reason: added example
 
Old 09-04-2011, 08:02 PM   #8
silentkill89
LQ Newbie
 
Registered: Aug 2011
Posts: 28

Original Poster
Rep: Reputation: Disabled
the string of integers is for client side to enter. What i want to do is when the client server has connected,client will type whatever to the server, and server will respond whatever again to the client. But what if client enter is not words but integers? If client enter like " Hello". In server it will display "Hello". If client enter "1234567". Then the server will add up the digits and display "28". That's the idea i want.I know there is something to do with the "%" thing, and i have never done the statement before. Also, i want to know how to test if the client enter a string that consist of all integers. Thank you for helping
 
Old 09-04-2011, 08:27 PM   #9
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD 9.1, Kubuntu 12.10
Posts: 3,078

Rep: Reputation: Disabled
Quote:
Originally Posted by silentkill89 View Post
the string of integers is for client side to enter. What i want to do is when the client server has connected,client will type whatever to the server, and server will respond whatever again to the client. But what if client enter is not words but integers? If client enter like " Hello". In server it will display "Hello". If client enter "1234567". Then the server will add up the digits and display "28". That's the idea i want.I know there is something to do with the "%" thing, and i have never done the statement before. Also, i want to know how to test if the client enter a string that consist of all integers. Thank you for helping
Using the function in my previous post:
Code:
#include <stdlib.h>
#include <stdio.h>


int total(const char *sString)
{
    char *remainder = NULL;
    long value = strtol(sString, &remainder, 10);
    if ((remainder && *remainder) || value < 0) return -1;

    unsigned int total = 0;
    do total += value % 10;
    while ((value /= 10));

    return total;
}


int main(int argc, char *argv[])
{
    int I, value;
    for (I = 1; I < argc; I++)
    if ((value = total(argv[I])) < 0) printf("%s\n", argv[I]);
    else                              printf("%i\n", value);
}
Of course, total can be replaced by something like millgates suggested, as long as it returns -1 if a non-digit is encountered.
Kevin Barry
 
Old 09-04-2011, 08:44 PM   #10
silentkill89
LQ Newbie
 
Registered: Aug 2011
Posts: 28

Original Poster
Rep: Reputation: Disabled
im not sure where to put the for loop, so i simply give a shot
Code:
/* tcpserver.c */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int total(const char *sString)
{
char *remainder = NULL;
long value = strtol(sString, &remainder, 10);
if((remainder && * remainder) || value < 0) return -1;

unsigned int total = 0;
do total += value %10;
while((value /= 10));

return total;
}

int main(int argc, char *argv[])
{
        int I, value;
        int sock, connected, bytes_recieved , true = 1;  
        char send_data [1024] , recv_data[1024], str;       

        struct sockaddr_in server_addr,client_addr;    
        int sin_size;
        
        for (I = 1; I < argc; I++)
        if((value = total)argv[I])) < 0) 
        printf("%s\n", argv[I]);
        else
        printf(%i\n", value);
              
        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("Socket");
            exit(1);
        }

        if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int)) == -1) {
            perror("Setsockopt");
            exit(1);
        }
        
        server_addr.sin_family = AF_INET;         
        server_addr.sin_port = htons(5000);     
        server_addr.sin_addr.s_addr = INADDR_ANY; 
        bzero(&(server_addr.sin_zero),8); 

        if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))
                                                                       == -1) {
            perror("Unable to bind");
            exit(1);
        }

        if (listen(sock, 5) == -1) {
            perror("Listen");
            exit(1);
        }
		
	printf("\nTCPServer Waiting for client on port 5000");
        fflush(stdout);


        while(1)
        {  

            sin_size = sizeof(struct sockaddr_in);

            connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);

            printf("\n I got a connection from (%s , %d)",
                   inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));

            while (1)
            {
              printf("\n SEND (q or Q to quit) : ");
              gets(send_data);
              
              if (strcmp(send_data , "q") == 0 || strcmp(send_data , "Q") == 0)
              {
                send(connected, send_data,strlen(send_data), 0); 
                close(connected);
                break;
              }
               
              else
                 send(connected, send_data,strlen(send_data), 0);  

              bytes_recieved = recv(connected,recv_data,1024,0);

              recv_data[bytes_recieved] = '\0';

       
              if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
              {
                close(connected);
                break;
              }

              else 
              printf("\n RECIEVED DATA = %s " , recv_data);
              fflush(stdout);
            }
        }       

      close(sock);
      return 0;
}
there errors keep saying at the total().
 
Old 09-04-2011, 09:31 PM   #11
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD 9.1, Kubuntu 12.10
Posts: 3,078

Rep: Reputation: Disabled
Quote:
Originally Posted by silentkill89 View Post
there errors keep saying at the total().
I'm not sure how I missed this, but I named a local variable total within the function total. Change the name of unsigned int total:
Code:
int total(const char *sString)
{
char *remainder = NULL;
long value = strtol(sString, &remainder, 10);
if((remainder && * remainder) || value < 0) return -1;

unsigned int sum = 0;
do sum += value %10;
while((value /= 10));

return sum;
}
That's probably not the problem, though. You definitely have a typo with if((value = total)argv[I])) < 0), however.

In my example I used argv just as an example source of strings to pass to total; you should pass total the lines received from the socket, but you must set the newline at the end of the line to 0 for total to work.
Kevin Barry
 
Old 09-04-2011, 09:32 PM   #12
silentkill89
LQ Newbie
 
Registered: Aug 2011
Posts: 28

Original Poster
Rep: Reputation: Disabled
Ok, i got the error. But although i get everything into fix, it still could not compute all the integers. Any help?
 
Old 09-04-2011, 09:41 PM   #13
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD 9.1, Kubuntu 12.10
Posts: 3,078

Rep: Reputation: Disabled
You should start by breaking your procedure down into smaller procedures so that the program flow makes more sense. You also can't expect to perform text communication with recv; you should fdopen the socket and fgets lines of input. I saw gets earlier and didn't notice that you used recv for the socket. You also need a condition to exit the loop when the socket is closed by the other end, not just when the other end sends "Q".

Basically you need to get to the point where reading and writing single lines at a time works reliably. After that you can do whatever you want with the lines you receive, such as totaling the digits.
Kevin Barry

Last edited by ta0kira; 09-04-2011 at 09:42 PM.
 
Old 09-04-2011, 09:52 PM   #14
silentkill89
LQ Newbie
 
Registered: Aug 2011
Posts: 28

Original Poster
Rep: Reputation: Disabled
hahaha. I tried some other way, but still it does not give what i want. and about you say set total to 0, i din quite get it. but i come up sumting lik this

/* tcpserver.c */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int total(const char *sString)
{
char *remainder = NULL;
long value = strtol(sString, &remainder, 10);
if ((remainder && *remainder) || value < 0) return -1;

unsigned int sum = 0;
do sum += value % 10;
while ((value /= 10));

return sum;
}


int main(int argc, char *argv[])
{
int I, value;
int sock, connected, bytes_recieved , true = 1;
char send_data [1024] , recv_data[1024], str;

struct sockaddr_in server_addr,client_addr;
int sin_size;


if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket");
exit(1);
}

if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int)) == -1) {
perror("Setsockopt");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero),8);

if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))
== -1) {
perror("Unable to bind");
exit(1);
}

if (listen(sock, 5) == -1) {
perror("Listen");
exit(1);
}

printf("\nTCPServer Waiting for client on port 5000");
fflush(stdout);


while(1)
{

sin_size = sizeof(struct sockaddr_in);

connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size); printf("\n I got a connection from (%s , %d)",
inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));

while (1)
{
printf("\n SEND (q or Q to quit) : ");
gets(send_data);

if (strcmp(send_data , "q") == 0 || strcmp(send_data , "Q") == 0)
{
send(connected, send_data,strlen(send_data), 0);
close(connected);
break;
}

else
send(connected, send_data,strlen(send_data), 0);

bytes_recieved = recv(connected,recv_data,1024,0);

recv_data[bytes_recieved] = '\0';

for (I = 1; I < argc; I++)
if ((bytes_recieved = total(argv[I])) < 0)
printf("%s\n", argv[I]);
else
printf ("%i\n", recv_data);


if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
{
close(connected);
break;
}

else
printf("\n RECIEVED DATA = %s " , recv_data);
fflush(stdout);
}
}

close(sock);
return 0;
}
 
Old 09-04-2011, 10:09 PM   #15
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD 9.1, Kubuntu 12.10
Posts: 3,078

Rep: Reputation: Disabled
I'm not actually sure what you're doing here. It looks like you're working on the server, but you're reading user input from standard input, which doesn't normally happen in a server. And where does the data go when you send it off? Where does the connection come from? You certainly don't need the loop over argv in your code, since main in my example was just setup so I could demonstrate using total both to detect non-integers and to sum digits. You should fdopen the socket immediately after a successful accept and use only that stream to read from and write to the socket since you're dealing with text. I really can't be of help with your code in its current state because I don't really know what's happening and what's supposed to be happening.
Kevin Barry
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Extracting integers from a string teresevo1 Programming 3 11-08-2010 08:24 PM
trouble adding days to a passed in date string ne00 Programming 5 04-08-2009 04:35 PM
Adding new functions in string class linux_chris Linux - Software 2 02-22-2009 02:59 PM
Adding Unsigned Integers of 128 bit bluechicken Programming 1 06-27-2005 02:27 PM
adding to vector<string> in a struct niteshadw Programming 3 02-03-2005 07:08 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:51 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration