简体   繁体   English

从第二个单词开始的文件行中的总和-C编程

[英]Sum numbers on line of a file starting from second word - C programming

Here is my input: 这是我的输入:

 david 10 40 70
 sam 9 45 31
 miranda 10 20 50
 zhang 10 26 41

I am trying to add all these numbers for each line and then print them out in terminal like this: 我试图为每行添加所有这些数字,然后像这样在终端中将它们打印出来:

david 120
sam 85
etc...

how do I sum these numbers starting from the second word in a line? 如何从一行中的第二个单词开始求和这些数字? Here's my code for some context: 这是我在某些情况下的代码:

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

 FILE *fr;
 char * line = NULL;
 size_t len =0;
 ssize_t read;

 int main(int argc, char* argv[]){

    fr = fopen(argv[1], "r");
        if(fr==NULL){
            exit(EXIT_FAILURE);
        }

         while ((read = getline(&line, &len, fr)) != -1){
            printf("%s", line );
        }
        fclose(fr);
        if (line){free(line);}
    return 0;
 }

You could try strsplit() ( EDIT : Or strtok() as @1.618 suggests, a bit different that PHP's strsplit) for each line, and then use atoi() . 您可以为每行尝试strsplit()编辑 :或按@ 1.618的建议使用strtok() ,与PHP的strsplit有点不同),然后使用atoi()

I'm not sure that strsplit() exists in C standard libraries, you may have to recode it yourself : it takes a char * (your string to split) and a char (the delimiter, in this case a space), and should return a char ** in which are your substrings (the words) you could pass to atoi() . 我不确定strsplit()是否存在于C标准库中,您可能必须自己对其重新编码:它需要一个char * (您要分割的字符串)和一个char (分隔符,在这种情况下为空格),并且应该返回一个char ** ,其中是您可以传递给atoi()的子字符串(单词

If your buffer is null terminated, you can do it in place, without special string splitting functions, and handle an arbitrary number of numbers. 如果缓冲区以null终止,则可以在不使用特殊字符串拆分功能的情况下就地进行处理,并可以处理任意数量的数字。

int sumline(char *buf)
{
  int sum=0;
  size_t i;
  for(i=0; buf[i] != '\0'; i++)
  {
    if(buf[i] == ' ' && isdigit(buf[i+1]))
    {
      sum += atoi(buf+i+1);
    }
  }
  return sum;
}

Just iterate over the characters, and whenever you hit a space, run atoi on the string starting from the next character. 只需遍历字符,每当您敲空格时,就从下一个字符开始对字符串运行atoi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM