簡體   English   中英

讀取帶有C空格的字符串

[英]Reading in a string with spaces in C

我試圖讀取一個字符串,可能包括也可能不包括空格ex。 “你好,世界”。 通過用戶輸入的數字選擇菜單進行以下操作。 這只是我想要做的一個小復制品。

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

int main(void){
  char line[3][80];

  strcpy(line[0],"default line 1\n");
  strcpy(line[1],"default line 2\n");
  strcpy(line[2],"default line 3\n");

  for(int i = 0; i < 3; i++){
    printf("%s", line[i]);
  }

  int option = 0;
  printf("would you like to replace line 1? (1 for yes)\n");
  scanf("%d",&option);
  if(option==1){
   printf("what would you like to replace the line with?\n");
   fgets(line[0],strlen(line[0]),stdin);
  }

  for(int i = 0; i < 3; i++){
    printf("%s", line[i]);
  }
}

為什么在我輸入1更改行之后,它會打印語句詢問我想要替換它的內容並自動輸入任何內容然后打印字符串,第一個字符串為空?

我也嘗試用sscanf("%[^\\n\\t]s", line[0]);讀取該行sscanf("%[^\\n\\t]s", line[0]); 沒有運氣。 有任何想法嗎?

這是因為

scanf("%d",&option);

在stdin中保留\\n字符,並在第一次調用fgets() 這就是為什么最好完全避免C中的scanf()

你可以修復它:

  scanf("%d",&option);
  getchar(); /* consume the newline */

但我建議使用fgets()來讀取option ,然后你可以使用strtol()將其轉換為整數。

請注意,此語句可能不是您想要的(這限制了您可以讀入line[0] )。

   fgets(line[0],strlen(line[0]),stdin);

你可能想要使用:

   fgets(line[0],sizeof line[0],stdin);

這樣你就可以讀到line[0]的實際大小。

請閱讀C Faq條目: http//c-faq.com/stdio/scanfprobs.html

使用fgets()通常看起來不像使用scanf()容易出錯,但是如果用戶輸入的字符串與指定的最大字符數一樣長或更長,則任何多余字符(包括換行符)都會保留在輸入流。 出於這個原因,我通常編寫自己的gets()版本來獲取用戶的輸入字符串,如果我想要數字輸入,我使用strtol() 以下是此類功能的示例:

char * s_gets(char *st, int n)
{
    char *ret;
    int ch;

    ret = fgets(st, n, stdin);
    if (ret) {
        while (*st != '\n' && *st != '\0')
            ++st;
        if (*st)
            *st = '\0';
        else {
            while ((ch = getchar()) != '\n' && ch != EOF)
                continue;           // discard extra characters
        }
    }
    return ret;
}

應用於OPs問題,我可能會這樣做:

#include <stdlib.h>                // for strtol()

...

char buf[80];
int option = 0;

printf("would you like to replace line 1? (1 for yes)\n");
s_gets(buf, sizeof(buf));
option = strtol(buf, NULL, 10);

if(option==1){
    printf("what would you like to replace the line with?\n");
    s_gets(line[0],sizeof(line[0]));
}

你的問題是'\\n'字符留在stdin並由fgets

我建議你總是使用fgets進行讀取輸入,所以

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

int main(void)
{
    char line[3][80];
    char temp[3];

    strcpy(line[0],"default line 1\n");
    strcpy(line[1],"default line 2\n");
    strcpy(line[2],"default line 3\n");

    for(int i = 0; i < 3; i++){
        printf("%s", line[i]);
    }

    int option = 0;
    printf("would you like to replace line 1? (1 for yes)\n");
    fgets(temp,sizeof(temp),stdin);
    option = atoi(temp);

    if(option==1){
        printf("what would you like to replace the line with?\n");
        fgets(line[0],sizeof(line[0]),stdin);
    }

    for(int i = 0; i < 3; i++){
    printf("%s", line[i]);
    }
}

暫無
暫無

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

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