0
我試圖找到獲得這種輸入的最佳方法: 「Word1 word2 1 2 3 4 -1」 基本上我想保存「這是一個字符串」,並將這些數字添加到可變和中,直到它們達到-1。在字符串中輸入字符,直到下一個字符爲整數 - C
我試着
scanf("%s %s", &string1, &string2);
它不能正常工作。
我試圖找到獲得這種輸入的最佳方法: 「Word1 word2 1 2 3 4 -1」 基本上我想保存「這是一個字符串」,並將這些數字添加到可變和中,直到它們達到-1。在字符串中輸入字符,直到下一個字符爲整數 - C
我試着
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末(雖然它確實ISN」見證第一行輸入),並且類似地,如果有超過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()
類似)來一次讀取所有值。
如何處理'他點了4杯啤酒...... 3 2 1 0 -1'? – alk
你可以給出另一個示例輸入和(預期)輸出嗎? – Linuxios
「Word1」中的「1」和「Word2」中的「2」都是字符串還是數字? –