簡體   English   中英

什么是 C 語言的 scanf("%*c") 的 C++ 等效項?

[英]What is the C++ equivalent of C language's scanf("%*c")?

客觀的:

  • 丟棄任何不需要的最簡單和類似的方法(在我的情況下是每個非數字字符,但我想要一個更一般情況的解決方案)並將它們從 buffer 中刪除 例子,
#include<stdio.h>
void main(void){
    int num1, num2;
    
    printf("Enter num1 here : ");
    scanf("%d%*[^\n]%*c", &num);//First scanf statement.
    
    printf("Enter num2 here : ");
    scanf("%d", &num2);//Second scanf statement.
    
    printf("num1  is : %d\n
            num2 is : %d", num, num2);
}

    /* OUTPUT */
    1st number : 25 asdfasfasfasf
    2nd number : 30
    Input 1 : 25
    Input 2 : 30
    /* This will work by discarding any non */
    /* In the program above I didn't write a printf statment to display the text "1st num, 2nd num". This is just so the output is a bit more clear. I am aware of it.  */

現在,如果您將第一個 scanf 從scanf("%d%[^\n]%*c"); scanf("%d"); 並給出相同的輸入,您將得到以下 output:

#include<stdio.h>

void main(void){
    int num1, num2;

    printf("Enter num1 here : ");
    scanf("%d", &num1);
    
    printf("Enter num2 here : ");
    scanf("%d", &num2);

    printf("num1 : %d\nnum2 : %d", num1, num2);
}
    //OUTPUT//
    Enter num1 here : 11 asdf
    Enter num2 here : num1 : 11
    num2 : 32764
   /*As you might see, I am not prompted for 2nd input. Instead the already present characters in the buffer are used.*/

簡報:

  • 在 C scanf("%d%[^\n]%*c"); 將刪除所有冗余字符,如空格、換行符、字母數字,這些字符在接受另一個輸入之前/之后形成緩沖區的數字之后。 我怎樣才能在 C++ 在我的cin >> var; 將獲取緩沖區中剩余的字符,然后丟棄它們。 這僅適用於 0-9 的數字。 但我感興趣的是*[^\n]*c因為它可以幫助我從緩沖區中讀取字符而不將它們保存在任何地方,這在技術上意味着它們被丟棄。

排除:

  • cin >> ws;
  • cin.ignore(numeric_limits::max(),'\n');

我已經找到了上述方法,但除非沒有其他更可行的選擇,否則我寧願不使用這些方法,因為它涉及包含外部庫#limits#vector接受。

在 C scanf("%[^\n]%*c"); 將在接受另一個輸入之前/之后從緩沖區中刪除所有冗余字符,如空格、換行符、alphaNumerics。

這在很多方面都是錯誤的。

  1. "%[^\n]%*c"掃描 1 個或多個非'\n' (嘗試保存它們),然后掃描 1 個'\n' 必須存在一個前導非'\n'否則掃描停止。 空格和字母數字沒有什么特別之處 - 只是'\n'和非'\n'

  2. 未定義的行為"%[^\n]"缺少用於保存輸入的匹配指針。 即使使用匹配的char * ,它也缺少寬度並且容易出現緩沖區溢出。 它比gets()更糟糕。

  3. 僅輸入"\n" ,不會消耗任何內容,也不會保存任何內容。 scanf("%[^\n]%*c"); 如果第一個字符是'\n' ,則無法使用任何內容。 如果不檢查返回值,調用代碼不知道是否讀取了任何內容。 匹配的char * (如果存在)未更改或可能不確定。

不要使用scanf("%[^\n]%*c"); 或其 C++ 等效std::scanf("%[^\n]%*c");

從 C++20 開始,您可能想要使用std::format 這基本上是在標准 C++ 中實現FMT

對於更復雜的場景,正則表達式應該會有所幫助。

暫無
暫無

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

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