我有下面的代碼,如果輸入字符串中沒有空格,它的工作原理。sscanf格式化輸入C++
char* input2 = "(1,2,3)";
sscanf (input2,"(%d,%d,%d)", &r, &n, &p);
這失敗以下輸入:
char input2 = " (1 , 2 , 3 ) ";
如何解決這一問題?
我有下面的代碼,如果輸入字符串中沒有空格,它的工作原理。sscanf格式化輸入C++
char* input2 = "(1,2,3)";
sscanf (input2,"(%d,%d,%d)", &r, &n, &p);
這失敗以下輸入:
char input2 = " (1 , 2 , 3 ) ";
如何解決這一問題?
簡單修復:在模式中添加空格。
char* input2 = "(1 , 2 , 3)";
sscanf (input2,"(%d, %d, %d)", &r, &n, &p);
模式中的空格消耗任何數量的空白,所以你很好。測試程序:
const char* pat="(%d , %d , %d)";
int a, b, c;
std::cout << sscanf("(1,2,3)", pat, &a, &b, &c) << std::endl;
std::cout << sscanf("(1 , 2 , 3)", pat, &a, &b, &c) << std::endl;
std::cout << sscanf("(1, 2 ,3)", pat, &a, &b, &c) << std::endl;
std::cout << sscanf("( 1 , 2 , 3)", pat, &a, &b, &c) << std::endl;
輸出:
3
3
3
3
此行爲是因爲從手動以下段落:
A directive is one of the following:
· A sequence of white-space characters (space, tab, newline, etc.;
see isspace(3)). This directive matches any amount of white space,
including none, in the input.
所有的scanf函數將把空間爲輸入終止字符,如果你想跳過空間,然後把空間放在任何你需要跳過它 – 2012-02-21 07:38:57