简体   繁体   English

在字符串中输入字符,直到下一个为整数-C

[英]Inputting chars in a string until the next one is an integer - C

I'm trying to find the best way to get this kind of input: "Word1 word2 1 2 3 4 -1" Basically I want to save "This is a string" in a string and add the numbers to a variable sum until they reach -1. 我正在尝试找到获得这种输入的最佳方法:“ Word1 word2 1 2 3 4 -1”基本上我想将“ This is a string”保存在字符串中,并将数字加到变量和中,直到它们达到-1。

I've tried with 我尝试过

scanf("%s %s", &string1, &string2);

It doesn't work properly. 它不能正常工作。

#include <stdio.h>

int main(void)
{
  char line[4096];
  while (fgets(line, sizeof(line), stdin) != 0)
  {
    char name1[32];
    char name2[32];
    int score = 0;
    int offset = 0;
    int length = 0;
    int number;
    if (sscanf(line + length, "%s%n", name1, &offset) != 1)
        break;
    length += offset;
    if (sscanf(line + length, "%s%n", name2, &offset) != 1)
        break;
    length += offset;
    while (sscanf(line + length, "%d%n", &number, &offset) == 1 && number != -1)
    {
      length += offset;
      score += number;
    }
    printf("%s %s %d\n", name1, name2, score);
  }
  return 0;
}

Data file: 资料档案:

John Smith 1 2 4 5
John Sutton 2 4 6 8 9 -1
Maggie Smith 9 8 9 8 9 9 -1

Sample output: 样本输出:

John Smith 12
John Sutton 29
Maggie Smith 52

You can fix it to object if there isn't a -1 at the end (though it really isn't needed, witness the first line of input), and similarly you can object if there are more than 6 entries, etc. 如果末尾没有-1,则可以将其固定为对象(尽管实际上并不需要,请见证输入的第一行),同样,如果条目数超过6,则可以反对。

Or, if you want to use fscanf() , then you can do this (which gives the same output for the given input as the original version): 或者,如果您想使用fscanf() ,则可以执行此操作(对于给定的输入,其输出与原始版本相同):

#include <stdio.h>

int main(void)
{
  char name1[32];
  char name2[32];
  int score[7];
  int nv;
  while ((nv = fscanf(stdin, "%31s %31s %d %d %d %d %d %d %d",
                name1, name2, &score[0], &score[1], &score[2], &score[3],
                &score[4], &score[5], &score[6])) > 2)
  {
    int total = 0;
    for (int i = 0; i < nv - 2; i++)
    {
        if (score[i] == -1)
          break;
        total += score[i];
    }
    printf("%s %s %d\n", name1, name2, total);
  }
  return 0;
}

Note that this code knows how many numbers were successfully read ( nv - 2 ), and proceeds accordingly. 请注意,此代码知道成功读取了多少个数字( nv - 2 ),并进行相应的处理。 Now your task is to go messing with the data file to see what other formats it accepts, and then decide whether this is better. 现在,您的任务是弄乱数据文件,以查看其接受的其他格式,然后确定是否更好。 You can also use a hybrid program, using fgets() to read a line and a sscanf() analogous to the fscanf() in the second program to read all the values at once. 您还可以使用混合程序,使用fgets()读取行,并使用sscanf()类似于第二个程序中的fscanf()来一次读取所有值。

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

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