[英]How to read string separated by / with scanf
我已經嘗試了很長時間了,經過一番研究后我沒有成功,所以我最后的辦法是提出一個問題。 我的輸入如下所示:
1.0.0.0/255.0.0.0/127.0.0.1/1112
1.2.0.0/255.255.0.0/2.4.6.9/1112
1.2.3.0/255.255.255.0/1.2.3.1/111
我需要從每一行中提取4個字符串,例如,第一行會給我
s1 = 1.0.0.0
s2 = 255.0.0.0
s3 = 127.0.0.1
s4 = 1112
這是我嘗試過的:
scanf("%s/%s/%s/%s", str1, str2, str3, str4); // This doesn't consume the "/"
scanf("%[^/]s%[^/]s%[^/]s%[^/]s", str1, str2, str3, str4); // This only gets the first string
scanf(""%[^\n]s%*c%s%*c%s%*c%s", str1, str2, str3, str4); // Hera %*c was supposed to consume the "/" and do not store it, it doen't happen tho
我如何在while (!feof(fileIn))
內使用單個scanf
從每個輸入行獲取4個字符串? 謝謝。
發布的代碼存在一些問題。 scanset指令為%[]
; 沒有s
在此。 使用%[^/]s
的格式字符串正在嘗試匹配輸入中的文字s
。 但這將始終失敗,因為%[^/]
匹配/
以外的任何字符。 遇到/
時,匹配失敗,並且/
字符保留在輸入流中。 在繼續下一個輸入字段之前必須消耗此字符。
另外, 請注意, while(!feof(file)){}
總是錯誤的 。 相反,嘗試使用fgets()
獲取輸入,並使用sscanf()
解析。 到達文件末尾時, fgets()
函數將返回空指針。
此外,在使用scanf()
系列函數讀取字符串時,應始終指定最大寬度,以避免緩沖區溢出。
這是一個示例程序:
#include <stdio.h>
int main(void)
{
char input[4096];
char str1[100];
char str2[100];
char str3[100];
char str4[100];
while (fgets(input, sizeof input, stdin)) {
sscanf(input, " %99[^/]/ %99[^/]/ %99[^/]/ %99[^/]",
str1, str2, str3, str4);
puts(str1);
puts(str2);
puts(str3);
puts(str4);
}
return 0;
}
使用來自問題的樣本輸入進行樣本交互:
λ> ./a.out < readstring_test.txt
1.0.0.0
255.0.0.0
127.0.0.1
1112
1.2.0.0
255.255.0.0
2.4.6.9
1112
1.2.3.0
255.255.255.0
1.2.3.1
111
您已經非常接近:您錯過了在第二種方法中使用分隔符的方法:
scanf("%[^/]/%[^/]/%[^/]/%[^/]", str1, str2, str3, str4);
應該做的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.