[英]How can I separate a string in 3 shorts and the rest in one string (this string as white spaces in it) in C?
如何將3個短褲之間以及其余字符串與4個不同字符串之間具有空格的字符串分隔開。
例:
"123 402 10 aaa bbb cc".
我想要的只是
short i=123;
short j=402;
short y=10;
char * c="aaa bbb cc".
我試圖使用sscanf
來做到這一點,但似乎無法讓最后一個字符串起作用而導致空白。
一種方法是:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char* str = "123 402 10 aaa bbb cc";
short i,j,y;
char c[256];
if (sscanf(str, "%hd %hd %hd %255[^\n]", &i, &j, &y, c) == 4) {
printf("i=%hd j=%hd y=%hd c=\"%s\"\n", i, j, y, c);
}
return 0;
}
並不困難:
#include <stdio.h>
int main() {
short i, j, y;
char text[80];
if (sscanf("123 402 10 aaa bbb cc\nsecond line", "%hd %hd %hd %79[^\n]", &i, &j, &y, text) == 4) {
printf("success: i=%d, j=%d, y=%d, text=%s\n", i, j, y, text);
}
return 0;
}
請注意,您必須自己為字符串分配緩沖區,並確保沒有緩沖區溢出發生。
您不需要sscanf
。 您可以使用strchr
查找空格,使用atoi
將字符串轉換為整數,並使用簡單賦值將空格轉換為終止零。
您也可以這樣做:
#include <stdio.h>
int main(void)
{
const char *test="123 402 10 aaa bbb cc";
short i, j, y;
char c[128];
sscanf(test, "%hd%hd%hd %[^\n]s", &i, &j, &y, c);
printf("i=%d j=%d y=%d c='%s'\n", i, j, y, c);
}
產量: i=123 j=402 y=10 c='aaa bbb cc'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.