簡體   English   中英

在字符串中輸入字符,直到下一個為整數-C

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

我正在嘗試找到獲得這種輸入的最佳方法:“ Word1 word2 1 2 3 4 -1”基本上我想將“ This is a string”保存在字符串中,並將數字加到變量和中,直到它們達到-1。

我嘗試過

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

它不能正常工作。

#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;
}

資料檔案:

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

樣本輸出:

John Smith 12
John Sutton 29
Maggie Smith 52

如果末尾沒有-1,則可以將其固定為對象(盡管實際上並不需要,請見證輸入的第一行),同樣,如果條目數超過6,則可以反對。

或者,如果您想使用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;
}

請注意,此代碼知道成功讀取了多少個數字( nv - 2 ),並進行相應的處理。 現在,您的任務是弄亂數據文件,以查看其接受的其他格式,然后確定是否更好。 您還可以使用混合程序,使用fgets()讀取行,並使用sscanf()類似於第二個程序中的fscanf()來一次讀取所有值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM