簡體   English   中英

基本的string.h問題(C ++)

[英]Basic string.h question (C++)

我有一個簡單的C ++文件,盡管我想更改它,但它會從文本文件中刪除字符。

文本字符串如下:

XXXXX | YYYYYYYYYYYYYYYYYYYYY

目前,它已刪除

| YYYYYYYYYYYYYYYYYYYYYY

從字符串中刪除,盡管我希望將其刪除:

XXXXX |

相反,實際上是去掉左側而不是右側。

我目前的代碼是:

#include <stdio.h>
#include <string.h>

main(int argc, char *argv[])
{
    char s[2048], *pos=0;
    while (fgets(s, 2048, stdin))
    {
        if (pos = strpbrk(s, "|\r\n"))
            *pos='\0';
        puts(s);
    }
    return 0;
}

您應該很少在C ++程序中使用<string.h>

您可能應該使用<string> ; 您可能使用<cstring>

這甚至不需要看代碼就可以了-如果您正在編寫C ++,請忘記<string.h>存在。 它是C功能的C標頭。 類似的注釋適用於<stdio.h> ; 它是一個C標頭,很少應在C ++中使用(通常使用<iostream>或偶爾使用<cstdio> )。

您的main()函數需要一個int的返回類型(在C ++和C99中)。 由於您需要管道之后的信息,因此可以編寫(一個完全有效的C(C89,C99)程序-完全不使用C ++的任何獨特功能,盡管C ++編譯器也可以接受):

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char s[2048];
    while (fgets(s, sizeof(s), stdin))
    {
        char *pos = strpbrk(s, "|\r\n");
        if (pos != 0)
            fputs(pos+1, stdout);
    }
    return 0;
}

使用fputs()而不是puts()來避免對輸出進行雙重間隔。

使用另一個數組,並在讀取XXXXX時分配目標數組中的字符。 當您遇到| 在源字符串中,在目標字符串中分配“ \\ 0”。 或者,如果您不想使用其他輔助陣列,則需要將帶有“ Y”的零件的開頭移到陣列的前面。 為此,您需要將一個計數器固定到數組(i)的底部(您要在其中移動下一個部分),然后將字符串掃描到具有第一個'Y'的部分,並將其存儲到另一個計數器(j) 。 現在,當j

這是移位版本,僅使用一個數組。

#include <stdio.h>
#include <string.h>

int main (void)
{
  char s[1024];
  int i, j, n;
  printf ("\ns: ");
  scanf (" %[^\n]", s);
  n = strlen (s);

  i = j = 0;
  /* Find the dilimeter index */
  while ((j < n) && s[j] != '|')
   j++;
  /* Move the other side of the dilimeter to
   * the begining pointed by index i. note that
   * we avoid the delimeter to be copied by 
   * pre-incrementing the counter j
   */
  while (j<n)
   s[i++] = s[++j];

  s[i] = '\0'; /* Terminate String */

  printf ("\n%s\n", s);
  return 0;
}

在這種情況下,2數組版本基本相同。

strpbrk()返回'|'的位置 ,因此只需使用它來輸出左修剪的字符串。 以下將輸出|YYYYYYYYYYYYYYYY 您需要對其稍加修改以刪除開頭的 '|'

#include <stdio.h>
#include <string.h>

main(int argc, char *argv[])
{
    char s[2048], *pos=0;
    while (fgets(s, 2048, stdin))
    {
        if (pos = strpbrk(s, "|\r\n"))
            puts(pos);
    }
    return 0;
}

暫無
暫無

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

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